4 ms·
Same thing with scala or clojure. If the object is mutable setters and other methods can still mutate it
by AzzieElbab 9y ago
Same thing with scala or clojure. If the object is mutable setters and other methods can still mutate it
- lmm 9y agoIn Scala it's much less of an issue because the culture is immutable-first, and the library ecosystem is established enough that you don't often have to resort to a mutability-oriented Java library. I understand things are similar for Clojure.
- tormeh 9y agoI'm really annoyed by val as well, but the standard library is immutable-first so it's never really a problem for things you haven't written yourself. It can probably be a real pain for larger software with lots of invented-here classes, made by former Java devs, though.
- sjrd 9y agoNo that's true for Scala. Scala has, in fact three kinds of "properties": * `val foo: Int`: always immutable, really. Every access always returns the same value * `var foo: Int`: mutable * `def foo: Int`: "getter" of sorts; cannot be written to, but can return different values when called several times
- the_af 9y agoupvoted, but I think you meant "that's NOT true for Scala" (for the reasons you mentioned). Also, it should be clarified that `val` in Scala gets evaluated only once, which is why it cannot return different things at different times, unlike `def`.
- benjaminjackman 9y agoYou could also mention 'def foo_=(x: Int) : Unit' which is a setter. 'lazy val foo: Int' which is immutable but doesn't execute its right hand side until the first time it called and then stores and returns the value returned by the right hand side everytime. not that they are different enough to be mentioned
- kod 9y agoThat's not really accurate either. val foo: Object will always return the same reference, but the state of the referenced object may have been mutated, which isn't what I'd expect when you say "always immutable, really".
- the_af 9y agoIt's subtle, but you're both saying different things. What happens with Kotlin cannot happen with Scala `val`s. Note in Kotlin it may return something entirely different, not just the same reference to a mutable object. It seems that in Kotlin a `val` may get evaluated every time it's called, whereas in Scala it can only be evaluated once. In Scala it cannot happen that you call a `val` twice and it returns a different object.
- the_af 9y agoAt first I thought the same as you, but the problem is actually subtler. It's not about an immutable reference to a mutable object, but actually a reference that gets re-evaluated each time it's invoked, which is something that cannot happen with Scala `val`s!