具有类型 class 要求的无形 HList foldLeft 正在运行

Shapeless HList foldLeft with type class requirement in operation

我正在尝试 运行 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)

我发现自己对接下来要尝试什么感到茫然...

您的类型类实例不在隐式范围内。将对象重命名为 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