本文介绍了为什么嵌套实例化中没有可用的 TypeTag(当由 Scala 代码运行器解释时)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据其类型参数修改 List.toString 的行为.由于 List 不能被扩展,它被一个自定义类 CList 包裹(可能是隐式的,但问题会保持不变?).打印 CListCList 时出现问题.以下是评论中的示例和相应输出:

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

推荐答案

我能够将代码减少到:

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

当它与scala解释器一起运行时,它给出一个错误No TypeTag available for this.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
  }
}

因此,编译器似乎无法为方法中定义的类生成类型标记.使用 -Xlog-implicits 运行会抱怨 无法创建引用本地类 Main.B 的 TypeTag:改用 Wea​​kTypeTag.

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.

这篇关于为什么嵌套实例化中没有可用的 TypeTag(当由 Scala 代码运行器解释时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:52