3 ms·
No 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 valu
by sjrd 9y ago
No 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.