Scala immutable objects and traits with val fields

后端 未结 5 1330
难免孤独
难免孤独 2021-02-08 03:04

I would like to construct my domain model using immutable objects only. But I also want to use traits with val fields and move some functionality to traits. Please look at the f

5条回答
  •  野性不改
    2021-02-08 03:17

    It's difficult to see how this would work and be consistent with Scala's semantics -- in particular, the semantics of an immutable field defined in a trait. Consider the Versionable trait:

    trait Versionable {
       val version = 0
    }
    

    This declaration says that, unless overridden, the version field will always have the value 0. To change the value of version "without polluting the class constructor with trait fields" (i.e. without explicitly overriding the version field) would violate these semantics.

提交回复
热议问题