Why won't this compile? ``` class Foo(var values: ...
# getting-started
b
Why won't this compile?
Copy code
class Foo(var values: MutableList<String>)

class Bar(var foo: Foo) {
    fun bar() {
        foo.values += "Baz"
    }
}
k
There's an ambiguity between
Collections.plus
and
MutableList.plusAssign
. The former is only applicable when the field is a
var
, so a fix would be to make it a val. I don't think you can even have a
var list: MutableList
with`+=` working.
b
That seems like something that should be fixed...
k
I don't really think there's even a fix.
b
Swift addresses this by having just one
struct
for both mutable and immutable versions, and then marking specific functions as
mutating
. At declaration time,
var
means "use the mutable version" and
let
means "use the immutable version. Copy-on-write ensures you don't mutate an immutable value passed to you. So:
Copy code
let array = [1, 2, 3]
array += 4 // compiler error
var array2 = array // copy
array2 += 4 // OK
print(array) // [1, 2, 3]
print(array2) // [1, 2, 3, 4]
k
Well Kotlin doesn't have actual immutability nor any mutating guarantees about methods (yet), so I don't think that would work here.
b
🙏 Valhalla...