我正在与Shapeless一起玩耍,探索在没有形状的标记记录中提取值类型的可能性。这样做的动机是我可以使用类型类和隐式类型来基于类型调度流程。 但是,以下代码不起作用。
import shapeless._, record._
import shapeless.ops.record.Selector
import shapeless.syntax.RecordOps
import shapeless.syntax.singleton._
object ShapelessRecordTest extends App {
trait Extractor[K, T] {
type OUT_K
def extract: T => OUT_K
}
object Extractor {
type Aux[K, T, OUT_K0] = Extractor[K, T] {
type OUT_K = OUT_K0
}
implicit def apply[T, Repr, OUT](k: Witness)(
implicit gen: LabelledGeneric.Aux[T, Repr],
selector: Selector.Aux[Repr, k.T, OUT]
): Aux[k.T, T, OUT] = new Extractor[k.T, T] {
type OUT_K = OUT
def extract: T => OUT_K = (e: T) => {
val rep = gen.to(e)
val rprOp: RecordOps[Repr] = new RecordOps[Repr](rep)
rprOp(k)
}
}
}
case class Person(name: String, address: String, age: Int)
implicit val gen = LabelledGeneric[Person]
val nameWit: Witness = 'name
val nameExtractor: Extractor.Aux[nameWit.T, Person, String] = Extractor(nameWit)
def main(args: Array[String]): Unit = {
val joe = Person("Joe", "Brighton", 33)
println(nameExtractor.extract(joe))
}
}
我正在使用Scala 2.12.8,编译器错误为
{
"resource": "/workspace/connecterra/stream-data-pipeline/flink/src/main/scala/io/connecterra/ShapelessRecordTest.scala",
"owner": "_generated_diagnostic_collection_name_#0",
"severity": 8,
"message": "could not find implicit value for parameter selector: shapeless.ops.record.Selector.Aux[Repr,ShapelessRecordTest.nameWit.T,OUT]",
"source": "scalac",
"startLineNumber": 37,
"startColumn": 74,
"endLineNumber": 37,
"endColumn": 75
}
我想了解我在这里想念的东西。还是完全没有形状?
答案 0 :(得分:1)
如果要显式调用apply
,则没有太大意义。最好不要混合使用实现方法和隐式方法来定义类型类的实例。 RecordOps
不应该手动创建(为此有import shapeless.record._
)。有时,最好直接调用类型类的apply
方法(例如shapeless.ops.record.Selector
),而不要依赖扩展方法。当您编写val nameWit: Witness = 'name
时,将失去类型细化功能。创建implicit val gen = LabelledGeneric[Person]
没有意义。对于Selector
,Repr
应该是<: HList
。
尝试
import shapeless._
import shapeless.ops.record.Selector
object ShapelessRecordTest {
trait Extractor[K, T] {
type OUT_K
def extract: T => OUT_K
}
object Extractor {
type Aux[K, T, OUT_K0] = Extractor[K, T] {
type OUT_K = OUT_K0
}
def apply[T](k: Witness)(implicit
extractor: Extractor[k.T, T]): Aux[k.T, T, extractor.OUT_K] = extractor
implicit def extractor[T, Repr <: HList, K](implicit
gen: LabelledGeneric.Aux[T, Repr],
selector: Selector[Repr, K]
): Aux[K, T, selector.Out] = new Extractor[K, T] {
type OUT_K = selector.Out
def extract: T => OUT_K = (e: T) => {
val rep: Repr = gen.to(e)
selector(rep)
}
}
}
case class Person(name: String, address: String, age: Int)
val nameWit = Witness('name)
val nameExtractor: Extractor.Aux[nameWit.T, Person, String] = Extractor(nameWit)
def main(args: Array[String]): Unit = {
val joe = Person("Joe", "Brighton", 33)
println(nameExtractor.extract(joe)) // Joe
}
}