HI everyone I'm seeing some Kotlin compiler behavi...
# announcements
a
HI everyone I'm seeing some Kotlin compiler behaviour, which seems to me a bit strange or at least looks like a compiler is too smart with type inference. Here are two functions and some class that holds
Map<,>
. First function compiles, although there was no explicit cast of
immutable
to
MutableMap
. Second function throws compiler error. Is this a desired behaviour?
Copy code
class Foo(val map : Map<Int, String>)
fun test1() {
    val foo = Foo(mutableMapOf(1 to "1"))
    val mutable = foo.map as MutableMap // cast is first
    val immutable =  foo.map

    mutable[0] = "1"
    immutable[0] = "1" // no error, looks like compiler infers "immutable=foo.map" as MutableMap
}

fun test2() {
    val foo = Foo(mutableMapOf(1 to "1"))
    val immutable =  foo.map
    val mutable = foo.map as MutableMap // cast is second

    mutable[0] = "12"
    immutable[0] = "12" // compiler error
}