我试图在HList上运行foldLeft,其中折叠函数需要类型类。下面的说明性示例在我引入包含异常
的类型类组件的那一刻就无法运行trait MyTypeClass[T] {
def apply(t: T): String
}
object MyTypeClasses {
implicit val myInt = new MyTypeClass[Int] {
def apply(t:Int) = s"Int($t)"
}
implicit val myString = new MyTypeClass[String] {
def apply(t:String) = s"String($t)"
}
implicit val myBoolean = new MyTypeClass[Boolean] {
def apply(t:Boolean) = s"Boolean($t)"
}
}
object FoldPoly extends Poly2 {
implicit def foldToStringBuffer[U](implicit M:MyTypeClass[U]) =
at[StringBuffer, (String, U)] { (acc, t) => acc.append(t._1).append(M(t._2)) }
}
object TestRunner {
def main(args:Array[String]):Unit = {
val h = ("one" -> 1) :: ("two" -> "2") :: ("three" -> false) :: HNil
println(h.foldLeft(new StringBuffer())(FoldPoly).toString)
}
}
失败:
Error:(68, 43) could not find implicit value for parameter folder:
shapeless.ops.hlist.LeftFolder[(String, Int) :: (String, String) :: (String, Boolean) :: shapeless.HNil,StringBuffer,FoldPoly.type]
println(h.foldLeft(new StringBuffer())(FoldPoly).toString)
我发现自己不知道接下来要尝试什么......
答案 0 :(得分:2)
您的类型类实例不在隐式范围内。将对象重命名为MyTypeClass
,以便将其视为随播广告或导入其内容:
object TestRunner {
def main(args:Array[String]):Unit = {
import MyTypeClasses._
val h = ("one" -> 1) :: ("two" -> "2") :: ("three" -> false) :: HNil
println(h.foldLeft(new StringBuffer())(FoldPoly).toString)
}
}