[英]Why there is no TypeTag available in nested instantiations (when interpreted by scala code runner)?
我試圖根據其類型參數修改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, 2), List(3, 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 available for this.A
看看解釋器生成的代碼,我想出了編譯器無法處理的代碼:
class Main {
class A
def main(args: Array[String]) {
class B
implicitly[TypeTag[A]] // ok
implicitly[TypeTag[B]] // error
}
}
看來,編譯器無法為方法中定義的類生成類型標記。 使用-Xlog-implicits
運行抱怨cannot create a TypeTag referring to local class Main.B: use WeakTypeTag instead
。
適合我,scala 2.10.2,輸出是:
[1, 2]
ab
[List(1, 2), List(3, 4)]
[[1, 2], [3, 4]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.