是否有可能scala超类将此作为子类

时间:2016-05-12 01:55:59

标签: scala

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

那么如何使method返回子类类型,以便我可以按任何顺序链接操作。

到目前为止,我能想到的是遵循类似

的内容
abstract class SuperClass[T <: SuperClass[T]]

但我不知道如何继续这样做。

2 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

abstract class SuperClass {
  def method(): this.type = this
}

答案 1 :(得分:3)

我发现以下方法也有效:

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()