The Actor
trait in Scala is defined like so,
/**
* User overridable definition the strategy to use for supervising
* child actors.
*/
def supervisorStrategy: SupervisorStrategy = SupervisorStrategy.defaultStrategy
However i see that all example code of concrete actors are defined as follows,
override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) {
...
}
What i am trying to understand is why is the supervisorStrategy
overridden as a val
?
Why not override it as a def
?
Is it because of the memory considerations , like we dont want this evaluation every time the method is called ?
So first up a scala trait
is a place to keep abstract definitions that we know would generally need overriding. Hence there is really no point in defining a method as val
, except for cases where the method is meant to be called by all concrete extensions of that trait
.
Typically when we extends a trait
with a def
method we have all options open . That is we can override it as a def
, a val
or a lazy val
.
The choice depends on the use case more often.
In this case we do not expect the supervisor strategy to change each time the superVisorStrategy
method is called from the akka subsystem. So once the method has executed we wish to hold on to the value for the future thus saving on some memory.
Hence it is defined as a val
or a lazy val
in most examples.