Class 为什么清单在构造函数中不可用?

Class 为什么清单在构造函数中不可用?,class,scala,types,constructor,manifest,Class,Scala,Types,Constructor,Manifest,考虑以下代码: class Foo[T : Manifest](val id: String = manifest[T].erasure.getName) 我基本上希望在Foo中存储一个标识符,它通常只是类名 不需要特殊标识符的子类可以很容易地使用默认值 但这甚至没有编译,错误消息是: error: No Manifest available for T. 还有其他可行的方法吗 编辑: 如果清单在主构造函数之前不可用,为什么要这样做 class Foo[T: Manifest](val na

考虑以下代码:

class Foo[T : Manifest](val id: String = manifest[T].erasure.getName)
我基本上希望在Foo中存储一个标识符,它通常只是类名

不需要特殊标识符的子类可以很容易地使用默认值

但这甚至没有编译,错误消息是:

error: No Manifest available for T.
还有其他可行的方法吗

编辑:

如果清单在主构造函数之前不可用,为什么要这样做

class Foo[T: Manifest](val name: String) { 
  def this() = this(manifest[T].erasure.getName)
}

当从该上下文绑定中删除语法糖时,它将被重写为:

class Foo[T]
  (val id: String = implicitly[Manifest[T]].erasure.getName)
  (implicit ev$1: Manifest[T]) = ...
因此,在确定
id
的默认值时,清单证据根本不可用。相反,我会这样写:

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)
}

>是的,清单<强> >在调用<代码>清单[t]。擦除< /代码> < /p>但不创建多余字段吗?为了避免多余字段,请从<代码> ID0 KIPTN的定义中删除<代码> Value/Cult>修饰符。gone@soc-通常最好避免使用下划线,重载符号,除非规范要求。不是答案,但如果您使用

manifest[T]
而不是隐式地使用
manifest[T]
,代码会更干净。