【发布时间】:2017-02-27 23:36:16
【问题描述】:
假设我有一个包含多个子类的超类。对于这些类中的每一个,我都希望有一个 updatePropertyX 方法来更新属性 x 并返回该类的新实例。
另外,我希望超类是抽象的,并且我只想实现这个updatePropertyX 方法一次。
这是我迄今为止尝试过的:
class Super(val name: String, val x: String)
{
def identify = println("This is a Super with properties" +
s"\n\tName: ${this.name}\n\tData: ${this.x}")
def updateX(newX: String): Super = new Super(name, newX)
}
class Sub_1(name: String, x: String) extends Super(name, x)
{
override def identify = println("This is a Sub_1 with properties" +
s"\n\tName: ${this.name}\n\tData: ${this.x}")
}
class Sub_2(name: String, x: String) extends Super(name, x)
{
override def identify = println("This is a Sub_2 with properties" +
s"\n\tName: ${this.name}\n\tData: ${this.x}")
}
val s1 = new Sub_1("sub1", "original data")
s1.identify
/*
This is a Sub_1 with properties
Name: sub1
Data: original data
*/
val s2: Sub_1 = s1.updateX("new data")
但是最后一行出现类型不匹配错误:找到Super,预期Sub_1(也不是我想要的抽象Super)。
我也试过把方法拉出来:
def updateSubX[T <: Super](orig: T, newX: String): T = new T(orig.name, newX)
val s2 = updateSubX(s1, "new data")
但这是有问题的,因为我认为您不能基于类型参数实例化一个类(因为擦除?)。
关于如何让它发挥作用有什么想法吗?
【问题讨论】: