Vlad Balan
03/03/2020, 4:08 PMkotlin
) behavior when running the following example:
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:
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
:
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!Kris Wong
03/03/2020, 4:10 PMkpgalligan
03/03/2020, 4:29 PMVlad Balan
03/03/2020, 4:30 PMkpgalligan
03/03/2020, 4:30 PMobject
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.