In my multiplatform project I created a simple str...
# kotlin-native
k
In my multiplatform project I created a simple structure to implement DI manually, main part of it are
Provider<T>
interface and
Singleton<T>
abstract class (code in thread). It works very well, however when I’m testing it on iOS I’m keep getting
Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen
when trying to
get()
on
Singleton
. How can I fix it without using
object
and
ThreadLocal
?
Copy code
internal interface Provider<T> {
    fun get(): T
}

internal abstract class Singleton<T : Any>: Provider<T> {
    private lateinit var t: T

    protected abstract fun creator(): T

    override fun get(): T =
        if (::t.isInitialized) {
            t
        } else {
            creator().apply {
                t = this
            }
        }
}
Copy code
Function doesn't have or inherit @Throws annotation and thus exception isn't propagated from Kotlin to Objective-C/Swift as NSError.
It is considered unexpected and unhandled instead. Program will be terminated.
Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen <object>@292a828
    at 0   Independo                           0x0000000103d98406 ThrowInvalidMutabilityException + 438
    at 1   Independo                           0x0000000103fc6020 kfun:com.audioburst.library.di.providers.Singleton#get(){}1:0 + 320
    at 2   Independo                           0x0000000103fbe883 kfun:com.audioburst.library.di.Injector.$<init>$lambda-1$FUNCTION_REFERENCE$7.invoke#internal + 259
    at 3   Independo                           0x0000000103fc632e kfun:com.audioburst.library.di.providers.object-2.creator#internal + 126
    at 4   Independo                           0x0000000103fc5fb1 kfun:com.audioburst.library.di.providers.Singleton#get(){}1:0 + 209
    at 5   Independo                           0x0000000103fc2522 kfun:com.audioburst.library.di.Injector.$<init>$lambda-25$FUNCTION_REFERENCE$31.invoke#internal + 210
    at 6   Independo
t
use
AtomicReference
for Kotlin Native (or use the
stately
library to use it from common)
keep in mind that everything you store in that reference needs to be frozen
k
It works, thank you 🙂
👍 1