https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
w

william

03/07/2021, 8:58 PM
Hi all I am having trouble with an object getting frozen in its
init
block and then top level value assignments causing an exception. heres a min example:
Copy code
class Foo(bar: Bar) {
    init {
        CoroutineScope(Dispatchers.Default).launch { 
            bar.buzz()
        }
    }
    
    val a = 3
}
in the init block since bar is accessed, it seems like that is causing the entire foo object to also get frozen then when it gets to
val a = 3
during runtime - it complains about foo instance already being frozen. how can i go about fixing this?
m

mbonnin

03/07/2021, 9:01 PM
Maybe try initiliazing
a
before launching the coroutine ?
r

russhwolf

03/07/2021, 9:02 PM
If
bar
is just a constructor parameter and not a property of
Foo
(eg
val bar: Bar
) then I wouldn’t expect the whole
Foo
to get frozen by that init block.
but yeah try initializing
a
first
m

mbonnin

03/07/2021, 9:03 PM
Yep, agreed that I wouldn't expect the whole
Foo
to be frozen there.
You can also use
ensureNeverFrozen
, sometimes that helps debugging where something becomes frozen
w

william

03/07/2021, 9:11 PM
just checked my actual code, looks like i reference a constructor parameter, as well as a constructor property (didn't show that in my simplified code), so I'm guessing thats why it is frozen
so it sounds like i can't start up that coroutine in the
init
block like i am now hmm. maybe i'll need to add a
start
function on my class or similar
r

russhwolf

03/07/2021, 9:14 PM
If you started from something like this
Copy code
class Foo(val bar: Bar) {
    init {
        CoroutineScope(Dispatchers.Default).launch { 
            bar.buzz()
        }
    }
}
then you can refactor like this to avoid freezing
Foo
Copy code
class Foo(bar: Bar) {
    val bar = bar // need to suppress a warning here
    init {
        CoroutineScope(Dispatchers.Default).launch { 
            bar.buzz()
        }
    }
}
bar
will still be frozen but there won’t be a
this
reference inside the coroutine stuff to freeze the whole
Foo
w

william

03/07/2021, 9:20 PM
thanks guys for the help! i was able to change the constructor property to just a parameter and that fixed this one. Russell thats a neat trick - i'm hoping i wont need to use that but good to know
looking forward to this new memory model that they have talked about at times
3