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

前端 未结 4 1266
失恋的感觉
失恋的感觉 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

    The difference is mainly that you can implement/override a def with a val but not the other way around. Moreover val are evaluated only once and def are evaluated every time they are used, using def in the abstract definition will give the code who mixes the trait more freedom about how to handle and/or optimize the implementation. So my point is use defs whenever there isn't a clear good reason to force a val.

提交回复
热议问题