我正在尝试List.toString
根据其类型参数修改其行为。由于List
无法扩展,因此它由自定义类包装CList
(可能带有隐式,但问题会保持不变?)。打印 a CList
of CList
s 时出现问题。以下是评论中的示例和相应的输出:
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]"