In Scala, a val
can override a def
, but a def
cannot override a val
.
So, is there an advantage to declaring a trait
def
is evaluated by name and val
by value. This means more or less that val
must always return an actual value, while def
is more like a promess that you can get a value when evaluating it. For example, if you have a function
def trace(s: => String ) { if (level == "trace") println s } // note the => in parameter definition
that logs an event only if the log level is set to trace and you want to log an objects toString
. If you have overriden toString
with a value, then you need to pass that value to the trace
function. If toString
however is a def
, it will only be evaluated once it's sure that the log level is trace, which could save you some overhead.
def
gives you more flexibility, while val
is potentially faster
Compilerwise, traits
are compiled to java interfaces so when defining a member on a trait
, it makes no difference if its a var
or def
. The difference in performance would depend on how you choose to implement it.