简体   繁体   English

Scala超类是否有可能将此作为子类返回

[英]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.

相关问题 Scala - Superclass在其方法中实例化其子类? - Scala - Superclass instantiate its subclass in its method? Scala:不能继承抽象泛型超类 - Scala: Can't subclass abstract generic superclass Scala:如何在为SuperClass声明的Map中插入SubClass而不是Superclass - Scala: How to insert SubClass instead of Superclass in Map declared for SuperClass 当子类使用val实现它时,Scala抽象方法在超类中为null? - Scala abstract method is null in superclass when subclass implements it using val? scala:如何使超类的变量隐含在子类的范围内 - scala: how to make a superclass' variable implicit in the scope of the subclass Scala子类字段仅在成员函数中隐藏超类var - Scala subclass field hiding superclass var only within member function 具有子类对象的scala超类引用未调用子类方法 - scala superclass reference with sub class object not calling subclass method Scala:如何在超类上实现克隆方法,并在子类中使用它? - Scala: How can I implement a clone method on a superclass, and use it in a subclass? 提供子类实例代替超类时出现 Scala 错误? - Scala error when providing subclass instance in place of superclass? 在 Scala 3 中是否可以使用扩展方法覆盖超类中的方法? - Is it possible in Scala 3 overriding a method in superclass with extension methods?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM