scala implicit (6)

scala

ClassTag, TypeTag and WeakTypeTag

It’s a special case to resolve implicit ClassTag instance. If there’s no such instance in scope, the compiler will create one. It’s same for TypeTag and WeakTypeTag.

import scala.reflect.ClassTag

object ClassTagExample {
  def get[T: ClassTag](map: Map[String, Any], key: String): Option[T] = map.get(key) match {
	// T will be regarded as Object due to type erasure if no ClassTag
	case Some(v: T) => Some(v)
    case _ => None
  }

  def main(args: Array[String]): Unit = {
    val map = Map("str" -> "hello", "num" -> 1) 
    println(get[String](map, "str")) // Some("hello")
    println(get[Int](map, "num")) // Some(1)
    println(get[Int](map, "str")) // None
  }

}

ClassTag solves the problem caused by type erasure. If no instance is in scope, the compiler will supply one by calling the apply[T] method of ClassTag object. And then it can use the type info stored to check exact type match, so it will not happen that get[Int](map, "str") returns Some(”hello”) and incurs ClassCastException later due to type erasure.

7f800fb3-4629-4807-836e-1aa6ba7079a6

147fc527-0009-425e-903e-55f2da376a63