Reputation: 408
This question is somewhat hard to summarize. Following code block shows what I want to do. I have a base class like this:
`class Base {
def methA:String="ook"
def methB:Int=1
}
Also I have a derived class, where I want each subclass method to call the super class method twice, compare the results and throw an exception on mismatch (this is for a test scenario).
But if I write
class Derived extends Base {
private def callDoublyAndCompare[T](fun:()=>T) : T = {
val fst=fun()
val snd=fun()
if(fst!=snd) throw new RuntimeException(s"Mismatch fst=$fst != snd=$snd")
snd
}
override def methB:Int={
callDoublyAndCompare(() => super[Derived].methB)
}
}
Then this will not compile. The only way out of this problem sofar has been to extract a method in class Derived which only calls the superclass' methB and to call this from the lambda call.
Is there a better way?
Upvotes: 0
Views: 42
Reputation: 408
The original example was not fully complete insofar as the Derived class was defined as inner class of another scala class. After I moved out this inner class to the top level, the example from Praveen above suddenly worked.
Upvotes: 0
Reputation: 987
I understood you want to call super call method. Hope below is what you want.
You can call that as below with the key word super
only
(new Derived).methB
. This will call super call method in callDoublyAndCompare
twice as per your code .
class Derived extends Base {
private def callDoublyAndCompare[T](fun:()=>T) : T = {
val fst=fun()
val snd=fun()
if(fst!=snd) throw new RuntimeException(s"Mismatch fst=$fst != snd=$snd")
snd
}
override def methB:Int={
callDoublyAndCompare(() => super.methB) //kept only super
}
}
Upvotes: 1