简体   繁体   中英

Why there is no TypeTag available in nested instantiations (when interpreted by scala code runner)?

I am trying to modify the behavior of List.toString according to its type parameter. Since List can't be extended, it is wrapped by a custom class CList (could be with implicits, but the problem would remain the same?). The problem arises when printing a CList of CList s. Below are examples and respective output in comments:

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]"

I was able to reduce the code to:

import scala.reflect.runtime.universe.TypeTag
class A
implicitly[TypeTag[A]]

When it is run with scala interpreter, it gives an error No TypeTag available for this.A . Looking at code produced by the interpreter, I came up with code that compiler can't handle:

class Main {
  class A
  def main(args: Array[String]) {
    class B
    implicitly[TypeTag[A]] // ok
    implicitly[TypeTag[B]] // error
  }
}

So it seems, that the compiler can't generate type tags for classes defined inside methods. Running with -Xlog-implicits complains cannot create a TypeTag referring to local class Main.B: use WeakTypeTag instead .

Works for me, scala 2.10.2, the output is:

[1, 2]
ab
[List(1, 2), List(3, 4)]
[[1, 2], [3, 4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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