考虑这段代码:
class Foo[T : Manifest](val id: String = manifest[T].erasure.getName)
我基本上想在 Foo 中存储一个标识符,它通常只是类名。
不需要特殊标识符的子类可以轻松使用默认值。
但这甚至没有编译,错误消息是:
error: No Manifest available for T.
还有另一种可行的方法吗?
编辑:
如果 list 在主构造函数之前不可用,为什么这会起作用?
class Foo[T: Manifest](val name: String) {
def this() = this(manifest[T].erasure.getName)
}
最佳答案
当从上下文绑定(bind)中删除语法糖时,它会被重写为:
class Foo[T]
(val id: String = implicitly[Manifest[T]].erasure.getName)
(implicit ev$1: Manifest[T]) = ...
因此,在确定
id
的默认值时, list 证据根本不可用。 .我会写这样的东西:class Foo[T : Manifest](id0: String = "") {
val id = if (id0 != "") id0 else manifest[T].erasure.getName
}
在您的第二种方法中(顺便说一句,这是一个很好的解决方案!),期望重写类似于:
class Foo[T](val name: String)(implicit x$1: Manifest[T]) {
def this()(implicit ev$2: Manifest[T]) = this(manifest[T].erasure.getName)
}
所以是的, list 是 在调用
manifest[T].erasure
之前可用
关于class - 为什么 Manifest 在构造函数中不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294761/