Hi guys, I came across an unexpected (different t...
# kotlin-native
v
Hi guys, I came across an unexpected (different that
kotlin
) behavior when running the following example:
Copy code
object Test {

    private var test: String? = null

    fun changeVar() {
        test = "test"
        println("val changed")
    }
}

fun main(args: Array<String>) {
    Test.changeVar()
}
This works in
Kotlin
but in
kotlin-native
it throws the following exception:
Copy code
Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen test.Test@e1d7d8
        at kfun:kotlin.Throwable.<init>(kotlin.String?)kotlin.Throwable (0x22fc57)
        at kfun:kotlin.Exception.<init>(kotlin.String?)kotlin.Exception (0x22a7b5)
        at kfun:kotlin.RuntimeException.<init>(kotlin.String?)kotlin.RuntimeException (0x22a535)
        at kfun:kotlin.native.concurrent.InvalidMutabilityException.<init>(kotlin.String)kotlin.native.concurrent.InvalidMutabilityException (0x232ee5)
        at ThrowInvalidMutabilityException (0x233263)
        at MutationCheck (0x26367e)
        at kfun:cairo.Test.<set-test>#internal (0x242b50)
        at kfun:cairo.Test.changeVar() (0x242bbe)
        at kfun:cairo.main(kotlin.Array<kotlin.String>) (0x242c67)
        at Konan_start (0x242d6b)
        at Init_and_run_start (0x245f7b)
        at __libc_start_main (0x7fb745f461e3)
        at  (0x217029)
        at  ((nil))
If the
object Test
is changed to
class Test
:
Copy code
class Test {

    private var test: String? = null

    fun changeVar() {
        test = "test"
        println("val changed")
    }
}

fun main(args: Array<String>) {
    Test().changeVar()
}
then it works as expected. Did somebody encounter this behavior? Is this intended? Is yes, can somebody please explain why? Thanks in advance!
k
For Kotlin native you absolutely need to understand the state rules. I wrote a blog series on this which may be easier to digest: https://dev.to/touchlab/practical-kotlin-native-concurrency-ac7
v
Thanks
k
Summary, yes.
object
is global, so it can’t have mutable state. There are other ways to implement your example, but it’ll depend on what you’re trying to do.