Reputation: 1935
Im trying to run a foldLeft on an HList where the folding function requires a typeclass. The below illustrative example fails to run the moment I introduce the typeclass component with the included exception
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)
}
}
With the Failure:
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)
I find my self at a loss for what to try next...
Upvotes: 1
Views: 227
Reputation: 7353
Your typeclass instances are not in the implicit scope. Rename object to MyTypeClass
so it is considered a companion or import its contents:
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)
}
}
Works in scastie
Upvotes: 2