在操作

时间:2018-02-02 11:18:52

标签: scala shapeless

我试图在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)

我发现自己不知道接下来要尝试什么......

1 个答案:

答案 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)

  }
}

作品in scastie