[英]is it possible for scala superclass return this as subclass
abstract class SuperClass {
def method() = this
}
class SubClass1 extends SuperClass {
def method1() = this
}
class SubClass2 extends SuperClass {
def method2() = this
}
val obj1 = new SubClass1()
obj1.method1().method() // this is ok
val obj2 = new SubClass2()
obj2.method().method2() // this is not ok, as method returns a SuperClass,
// which has no method named method2
So how to make the method
return the subclass type so I can chain the operation in any order. 因此,如何使method
返回子类类型,以便可以按任何顺序链接操作。
So far what I can think is to follow something like 到目前为止,我能想到的是遵循
abstract class SuperClass[T <: SuperClass[T]]
but I don't know how to continue that. 但我不知道该如何继续。
Something like this should work: 这样的事情应该起作用:
abstract class SuperClass {
def method(): this.type = this
}
I find the following approach works as well: 我发现以下方法也适用:
abstract class SuperClass[T <: SuperClass[T]] {
def method(): T = this.asInstanceOf[T]
}
class SubClass extends SuperClass[SubClass] {
def method1() = this
}
val obj = new SubClass()
obj.method1().method()
obj.method().method1()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.