Search code examples
scalaimplicitscala-reflect

In Scala, why it is impossible to infer TypeTag from type alias or dependent type?


I have a simple scala program to test the Capability of Scala to infer type classes:

import scala.reflect.ClassTag

object InferTypeTag {

  import org.apache.spark.sql.catalyst.ScalaReflection.universe._

  def infer(): Unit = {
    type U = (Int, String)

    val ttg1 = implicitly[TypeTag[(Int, String)]]

    val ttg2 = implicitly[TypeTag[U]]

    val ctg = implicitly[ClassTag[U]]
  }
}

ttg1 got inferred without problem.

ttg2 triggered the following compilation error:

Error:(14, 26) No TypeTag available for U
    val ttg2 = implicitly[TypeTag[U]]

Question 1: why it doesn't work? type U is already final and is impossible to override

Question 2: if type U is not final and path-dependent, why ctg can be inferred successfully?


Solution

  • Maybe someone will explain why a local type looks abstract. Maybe just a bug.

    scala> import scala.reflect.runtime.universe._
    import scala.reflect.runtime.universe._
    
    scala> { type X = Tuple2[Int, String] ; weakTypeTag[X] }
    res0: reflect.runtime.universe.WeakTypeTag[X] = WeakTypeTag[X]
    
    scala> { type X = Tuple2[Int, String] ; typeTag[X] }
                                                   ^
           error: No TypeTag available for X
    
    scala> { type X = Tuple2[Int, String] ; weakTypeTag[X].tpe }
    res2: reflect.runtime.universe.Type = X