How to create an instance of a platform specific class in KMM?

318 views Asked by At

For example, I have the next class declarations:

// commonMain 
expect class MyUseCase {
    operator fun invoke()
}
// androidMain
actual class MyUseCase {
    actual operator fun invoke() {}
}
// iosMain
actual class MyUseCase {
    actual operator fun invoke() {}
}

Is there a way to create an instance of MyUseCase in commonMain?

// commonMain
val useCase = MyUseCase() // Doesn't work

P.S. It must be possible cuz Kotlin has information about actual implementations at the moment when it will create an instance of the class.

1

There are 1 answers

0
Phil Dukhov On BEST ANSWER

You need to add a constructor for your class:

// commonMain 
expect class MyUseCase() {
    operator fun invoke()
}
// androidMain
actual class MyUseCase actual constructor() {
    actual operator fun invoke() {}
}
// iosMain
actual class MyUseCase actual constructor() {
    actual operator fun invoke() {}
}