Search code examples
kotlinkotlin-multiplatformkotlin-multiplatform-mobile

Kotlin multiplatform expect/actual class , some methods shared


Is it possible to have some expect + abstract class in KMM? The project is Android+iOS

I want to have some shared class, but part of methods should be platform specific.

What is the best way to do this? Maybe some combination of expected class, shared parent for actual class?

Example,

expect class Logger {
    protected timer:Long = 0
    fun info(s:String)
    fun warning(s:String)
    fun resetTimer() {
         timer = 0
    }
}

As i understand such example is impossible, because expected class should be rather as interface than abstract class.

The method resetTimer could be same for both platforms.

Is it possible somehow?


Solution

  • Short answer is no.

    You can think of expect/actual as an abstraction over platform-specifics, similar to interfaces, but a lot less flexible (interfaces are abstractions over anything not just a platform specific implementation)

    There are multiple options, but in any case you need to separate the common logic from the expected declaration.