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

假如想象 提交于 2021-02-08 03:30:39

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/59708880/in-scala-why-it-is-impossible-to-infer-typetag-from-type-alias-or-dependent-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!