Home > Software design >  How to create an instance of a platform specific class in KMM?
How to create an instance of a platform specific class in KMM?

Time:04-21

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.

CodePudding user response:

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() {}
}
  • Related