<@U3D0A5GP9> I'd use `var`s with a private setter ...
# getting-started
a
@poohbar I'd use `var`s with a private setter and a
fun changeName(first, last)
👍 1
p
Yeah, seems like the only option but then I couldnt use data classes. I am a bit dissapointed with Kotlin's expresivness there
a
yeah, and you need to have constructor arguments + the properties, so everything twice
p
ugh 😕
that would actually look better in java
thats awful 😞
Does anyone have an idea how to make this better? Is there a delegate that could help me? I hate the field duplication because in practice I will have way more fields than that.
Copy code
class PersonKotlin(
    private var _firstName: String,
    private var _lastName: String,
    private var _updated: Instant
) {
    val firstName get() = _firstName
    val lastName get() = _lastName
    val updated get() = _updated

    fun changeName(firstName: String, lastName: String) {
        this._firstName = firstName
        this._lastName = lastName
        this._updated = Instant.now()
    }
}
.
a
Copy code
class PersonKotlin(
    _firstName: String,
    _lastName: String,
    _updated: Instant
) {
    var firstName = _firstName
        private set

    var lastName = _lastName
        private set

    var updated = _updated
        private set

    fun changeName(firstName: String, lastName: String) {
        this.firstName = firstName
        this.lastName = lastName
        this.updated = Instant.now()
    }
}
a
Personally I'd rather retain an immutable data class and have the
changeName
function return a copy of the instance with modified fields.
1
p
Yeah, I am actually trying to think about how I want to structure the domain. This was an attempt to implement an "entity" as described in Domain Driven Design by Eric Evans.
his idea is that some entities are in fact mutable in real life so why force them to be immutable?
e.g. customer's "Cart" has a total and a list of items, why should that be immutable?
a
An advantage is that you'll have less race conditions in multi-threaded-programs
a
We have recently been using CRDT's (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) to manage state which maybe changed simultaneously by multiple threads/nodes. Basically state is managed almost as an initial state followed by a set of subsequent actions and 'actions' be added (i.e. can insert event to item's history but cannot delete or update previous event) and so 'current state' =
initial state
+ sum of actions. NB - It's a bit more complex than that as system can roll up state + events to create interim snapshots. This maintains in effect maintains the immutability of the entities but allows updates (if that makes sense 🙂 )