Type Safe Cast

Type safe cast

shapeless provides a Typeable type class which provides a type safe cast operation. cast returns an Option of the target type rather than throwing an exception if the value is of the incorrect type, as can happen with separate isInstanceOf and asInstanceOf operations. Typeable handles primitive values correctly and will recover erased types in many circumstances

import syntax.typeable._

val l: Any = List(Vector("foo", "bar", "baz"), Vector("wibble"))
l.cast[List[Vector[String]]] should be(res0)
l.cast[List[Vector[Int]]] should be(res1)
l.cast[List[List[String]]] should be(res2)

An extractor based on Typeable is also available, allowing more precision in pattern matches,

val `List[String]` = TypeCase[List[String]]
val `List[Int]` = TypeCase[List[Int]]
val l = List(1, 2, 3)

val result = (l: Any) match {
  case `List[String]`(List(s, _*)) => s.length
  case `List[Int]`(List(i, _*)) => i + 1

result should be(res0)