为什么嵌套实例化中没有TypeTag(由scala代码运行符解释)?
发布时间:2020-12-16 18:40:57 所属栏目:安全 来源:网络整理
导读:我试图根据其类型参数修改List.toString的行为.由于List无法扩展,它被自定义类CList包装(可能带有隐含,但问题会保持不变?).打印CList CList时出现问题.以下是评论中的示例和相应输出: object Foo { import scala.reflect.runtime.universe._ class CList[A
我试图根据其类型参数修改List.toString的行为.由于List无法扩展,它被自定义类CList包装(可能带有隐含,但问题会保持不变?).打印CList CList时出现问题.以下是评论中的示例和相应输出:
object Foo { import scala.reflect.runtime.universe._ class CList[A: TypeTag](val l: List[A]) { override def toString = typeOf[A] match { case t if t =:= typeOf[Char] => l.mkString case _ => "[" + l.mkString(",") + "]" } } } import Foo.CList val c = new CList(List(1,2)) // prints "[1,2]" println(c) val c2 = new CList(List('a','b')) // prints "ab" println(c2) val c3 = new CList(List( List(1,2),List(3,4))) println(c3) // prints "[List(1,4)]" val c4 = new CList(List( new CList(List(1,2)),new CList(List(3,4)))) println(c4) // prints "No TypeTag available for this.Foo.C[Int]" 解决方法
我能够将代码减少到:
import scala.reflect.runtime.universe.TypeTag class A implicitly[TypeTag[A]] 当它使用scala解释器运行时,它会给出一个错误No TypeTag for this.A.看看解释器生成的代码,我想出了编译器无法处理的代码: class Main { class A def main(args: Array[String]) { class B implicitly[TypeTag[A]] // ok implicitly[TypeTag[B]] // error } } 看来,编译器无法为方法中定义的类生成类型标记.使用-Xlog-implicits运行抱怨无法创建引用本地类Main.B的TypeTag:改为使用WeakTypeTag. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |