在value classes 的规范中,它说:
值类只能扩展通用特征,不能扩展自身。通用特征是扩展的特征
Any
,只有def
s 作为成员,并且不进行初始化。通用特征允许对值类的方法进行基本继承,但它们会产生分配的开销。例如
trait Printable extends Any {
def print(): Unit = println(this)
}
class Wrapper(val underlying: Int) extends AnyVal with Printable
val w = new Wrapper(3)
w.print() // actually requires instantiating a Wrapper instance
第一个问题
现在,我认为这意味着以下(可能)不需要实例化:
trait Marker extends Any
class Wrapper(val underlying: Int) extends AnyVal with Marker {
def print(): Unit = println(this) //unrelated to Marker
}
val w = new Wrapper(3)
w.print() //probably no instantiation as print is unrelated to Marker
我对么?
第二个问题
而且我认为这是否需要实例化是有机会的:
trait Printable extends Any {
def print(): Unit //no implementation
}
class Wrapper(val underlying: Int) extends AnyVal with Printable {
override def print() = println(this) //moved impl to value class
}
val w = new Wrapper(3)
w.print() // possibly requires instantiation
在概率的平衡上,我也认为不需要实例化——我正确吗?
编辑
我没有考虑print()
示例中的确切实现:
def print(): Unit = println(this)
假设我使用了以下内容:
def print(): Unit = println(underlying)
这些会导致实例化吗?