为什么Manifest在构造函数中不可用? [英] Why is the Manifest not available in the constructor?

查看:188
本文介绍了为什么Manifest在构造函数中不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个代码:

  class Foo [T:Manifest](val id:String = manifest [T] .erasure .getName)



我基本上想在Foo中存储标识符,这通常只是类名。



不需要特殊标识符的子类可以方便地使用默认值。



t even compile,错误消息是:

 错误:没有清单可用于T. 


编辑:

$

b
$ b

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

  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 :Manifest [T])= this(manifest [T] .erasure.getName)
}

是,在调用清单[T] .erasure


之前,清单 Consider this code:

class Foo[T : Manifest](val id: String = manifest[T].erasure.getName)

I basically want to store an identifier in Foo, which is often just the class name.

Subclass which do not need a special identifier could then easily use the default value.

But this doesn't even compile, the error message is:

error: No Manifest available for T.

Is there another approach which will work?

EDIT:

Why does this work if the manifest isn't available until the primary constructor?

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

解决方案

When the syntactic sugar is removed from that context bound, it gets rewritten as:

class Foo[T]
  (val id: String = implicitly[Manifest[T]].erasure.getName)
  (implicit ev$1: Manifest[T]) = ...

So the Manifest evidence simply isn't available when determining the default value of id. I'd instead write something like this:

class Foo[T : Manifest](id0: String = "") {
  val id = if (id0 != "") id0 else manifest[T].erasure.getName
}


In your second approach (which is a great solution, by the way!), expect a rewrite similar to:

class Foo[T](val name: String)(implicit x$1: Manifest[T]) { 
  def this()(implicit ev$2: Manifest[T]) = this(manifest[T].erasure.getName)
}

So yes, the manifest is available before the call to manifest[T].erasure

这篇关于为什么Manifest在构造函数中不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆