有没有办法让方法总是返回调用它的同一个类的类型?
让我解释:
class Shape {
var mName: String = null
def named(name: String): Shape = {
mName = name
this
}
}
class Rectangle extends Shape {
override def named(name: String): Rectangle = {
super.named(name)
this
}
}
这是有效的,但是有没有一种方法可以做到这一点而不必覆盖
named
在我所有的子类中起作用?我正在寻找这样的东西(不起作用):class Shape {
var mName: String = null
def named(name: String): classOf[this] = { // Does not work but would be great
mName = name
this
}
}
class Rectangle extends Shape {
}
任何的想法 ?或者不可能?
最佳答案
您需要使用 this.type
而不是 classOf[this]
.
class Shape {
var mName: String = null
def named(name: String): this.type = {
mName = name
this
}
}
class Rectangle extends Shape {
}
现在来证明它的工作原理(在 Scala 2.8 中)
scala> new Rectangle().named("foo")
res0: Rectangle = Rectangle@33f979cb
scala> res0.mName
res1: String = foo
this.type
是编译类型名称,而 classOf
是一个在运行时被调用以获取 java.lang.Class
的运算符目的。您不能使用 classOf[this]
永远,因为参数需要是一个类型名称。尝试获取 java.lang.Class
时的两种选择对象是打电话classOf[TypeName]
或 this.getClass()
.
关于scala - 在 Scala 中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13048725/