在Scala中,为什么不可能从类型别名或从属类型推断TypeTag? [英] In Scala, why it is impossible to infer TypeTag from type alias or dependent type?

查看:64
本文介绍了在Scala中,为什么不可能从类型别名或从属类型推断TypeTag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的scala程序来测试Scala推断类型类的能力:

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 .

ttg2 触发了以下编译错误:

ttg2 triggered the following compilation error:

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

问题1 :为什么它不起作用?类型U已经是最终类型,无法覆盖

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

问题2 :如果类型U不是最终的且与路径相关,为什么可以成功推断ctg?

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

推荐答案

也许有人会解释为什么本地类型看起来很抽象.也许只是一个错误.

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

这篇关于在Scala中,为什么不可能从类型别名或从属类型推断TypeTag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆