Reputation: 7367
I have the following method:
class TestBase {
def base(value: Int) = println(value)
}
Now, I wanted to override it and add some function, performing side-effect which is supposed to bring into scope by caller. I mean caller will decide what side effect to add. I tried it like this:
class TestDerived extends TestBase{
override def base(value: Int)(implicit ev : Int => Unit) = println("Overriden")
//Error, Method 'base' overrides nothing
}
But this code refuses to compile. I suspected, but didn't know fore sure if implicits
are part of method's signature. So, is there any other way to let caller provide their own version of side-effect function. The reason I cannot just add implicit parameter to a base class is that I use akka.Actor
and I cannot modify signature of akka.actor.receive: Receive
.
Upvotes: 4
Views: 1222
Reputation: 28511
It is possible to achieve the same behaviour, but not through overriding the method. You have a couple of options:
1. Move the implicit to the constructor
class TestDerived()(implicit ev: Int => Unit) extends TestBase {
override def base(value: Int) {
println("Overriden")
}
}
2. Wrap the base method in another method
class TestDerived() extends TestBase {
def base2(value: Int)(implicit ev: Int => Unit): Unit = {
// implement whatever logic you want here.
ev(base(value))
}
}
Upvotes: 1
Reputation: 5275
I don't think it is posible
If I call the derived function by using base pointer:
val o: TestBase = new TestDerived
o.base(1)
Since the implicit parameter is added by compiler while compiling, but here the compiler only lookup the base function signature, so the compiler will not generate the implicit parameter.
Upvotes: 2