Is there any advantage to definining a val over a def in a trait?

前端 未结 4 1270
失恋的感觉
失恋的感觉 2021-02-05 16:56

In Scala, a val can override a def, but a def cannot override a val.

So, is there an advantage to declaring a trait

4条回答
  •  抹茶落季
    2021-02-05 17:26

    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.

提交回复
热议问题