Scala Traits and Inheritance

大兔子大兔子 提交于 2021-02-11 13:37:55

问题


I have my Scala classes structured as below:

trait ActualClass extends ParentClass {
  override def method1(inputStr:String):String = {
    "actual "+ inputStr
  }
  def execute():String = {
    this.method1("test")
  }
}

trait WithClass extends ParentClass {
  override def method1(inputStr:String):String = {
    "with "+ inputStr
  }
}

class ParentClass {
  def method1(inputStr:String):String = {
    "parent "+ inputStr
  }
}

object TestClass extends App{
  val actualClass = new ActualClass with WithClass {
  }
  println(actualClass.execute())
}

Observed Behavior:

  1. Using this.method1 in ActualClass execute method: prints "With Test"
  2. Using super.method1 in ActualClass execute method: prints "parent Test"

Expected Behavior: I need it to print: "Actual Test"

So how can I invoke the method1 that is within the ActualClass and not from WithClass or ParentClass. Is there a specific keyword for it.


回答1:


You can't call specifically ActualClass#method1 within ActualClass.

If you want result "actual test" you should define val actualClass vice versa

val actualClass = new WithClass with ActualClass

(method implementation is selected according to linearization order).

Generally you can't call specifically SomeClass#someMethod within SomeClass with this.someMethod. Implementation can always be overriden in an inheritor (unless the method is final). If you could this would be against OOP principles. You can't control this in such way. So X=ActualClass being the same in X#method1 and X#execute is irrelevant in this sense.

That's why there is syntax super[A].someMethod (in order not to rely on linearization) but not this[A].someMethod.

You can try also

trait ActualClass extends ParentClass {
  override def method1(inputStr:String):String = {
    "actual "+ inputStr
  }
  def execute():String = {
    (new ActualClass {}).method1("test")
  }
}


来源:https://stackoverflow.com/questions/63024762/scala-traits-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!