I have a value of type Any
. If its class is Map[String, Any]
I must be able to cast it to a case class and for this purpose I'm using the solution proposed by Travis Brown here. The problem is that when I define a Typeable
implementation as the following, in certain cases, I get the diverging implicit expansion error:
implicit def caseClassTypeable[T, R <: HList](implicit castT: Typeable[T],
gen: LabelledGeneric.Aux[T, R],
fromMap: FromMap[R]) =
new Typeable[T] {
override def cast(t: Any): Option[T] = t.cast[Map[String, Any]] flatMap (m => to[T].from(m))
override def describe: String = castT.describe
}
REPL session:
scala> import shapeless.syntax.typeable._
import shapeless.syntax.typeable._
scala> case class Simple(foo: String, bar: Int)
defined class Simple
scala> val m: Any = Map("foo" -> "a", "bar" -> 42)
m: Any = Map(foo -> a, bar -> 42)
scala> m.cast[Simple]
res7: Option[Simple] = Some(Simple(a,42))
scala> val l: Any = List(1, 2, 3)
l: Any = List(1, 2, 3)
scala> l.cast[List[Any]]
<console>:22: error: diverging implicit expansion for type shapeless.Typeable[List[Any]]
starting with method inrTypeable in object Typeable
l.cast[List[Any]]
^
However this one works:
scala> l.cast[List[Int]]
res9: Option[List[Int]] = Some(List(1, 2, 3))
Any idea?