简体   繁体   English

在 Scala 中,为什么不能从类型别名或依赖类型推断 TypeTag?

[英]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:我有一个简单的 Scala 程序来测试 Scala 推断类型类的能力:

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. ttg1被推断没有问题。

ttg2 triggered the following compilation error: ttg2触发了以下编译错误:

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

Question 1 : why it doesn't work?问题1 :为什么它不起作用? type U is already final and is impossible to override类型 U 已经是最终的并且不可能被覆盖

Question 2 : if type U is not final and path-dependent, why ctg can be inferred successfully?问题2 :如果类型U不是final且是path-dependent,为什么ctg可以推断成功?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM