Expected an compiler error, but it didn't came 😉
Is this expected behavior?
Copy code
class Dummy {
// Define as read-only access map
private val buffers: Map<String, String>
init {
buffers = mutableMapOf()
// Unexpected, no error
buffers["test"] = "hello"
}
fun dummy2() {
// Not allowed, as expected
buffers["test"] = "hello"
}
}
e
ephemient
06/03/2021, 6:52 PM
I think it's just smart casting, works in a local function too:
Copy code
fun main() {
val buffers: Map<String, String>
buffers = mutableMapOf()
buffers["test"] = "hello"
}
p
Peter
06/03/2021, 8:17 PM
I agree it is smart casting at work. I'm just not convinced smart casting should be done at assignment. Seems to break some common OO patterns of using abstractions like interfaces instead of implementations.
Another side effect is that the below two snippets behave differently, which might come as a surprise.
Copy code
// Works
val buffers: Map<String, String>
buffers = mutableMapOf()
buffers["test"] = "hello"