class - 为什么 Manifest 在构造函数中不可用?

标签 class scala types constructor manifest

考虑这段代码:

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/

相关文章:

php - 将任何类或任何方法声明为 "final"的示例场景是什么?

c++ - 实现动态创建的类对象数组(C++)

scala - Lift - 页面在 Firefox 中显示为 XML 而不是 HTML

c# - C# 中的所有引用类型都是类类型吗?

C 风格类型注解与其他注解

python - 为什么这个类变量在不同的实例中是相同的?

c# - 实例化的类对于每个用户来说都是唯一的吗?

scala - : org. scalamacros:quasiquotes 中冲突的跨版本后缀

mysql - tomcat connectionpool mysql配置避免空闲连接超时

jquery输入数字