问题
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:
- Using this.method1 in ActualClass execute method: prints "With Test"
- 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