Search code examples
javaandroidkotlinkotlin-multiplatformkmm

Passing Android / iOS specific arguments in Actual / Expect classes in Kotlin Mutliplatform project


So I'm trying to integrate KMM module into an already existing android app. I'm exposing a class from common KMM module into the Android project, which looks something like this (please ignore the syntax, it's written just for reference of what I'm doing) -

// Common KMM Module
import CustomDataType // THIS DOES NOT WORK COS IT"S AN ANDROID MODULE AND NOT MULTIPLATFORM
object CommonHandler {
    fun init(args: CustomDataType) { // ??? How can I receive custome Data type here ?????
        println("test init of Mission Handler")
        AndroidModule.init(args); // How can I pass into the android KMM module
    }
}

expect object AndroidModule {
  fun init(args: CustomDataType)
}

// ANDROID KMM Module 

import CustomDataType; // I can import the data type here though
actual object AndroidModule {
    actual fun init(args: CustomDataType)
}


// MAIN ANDROID APP

import CommonHandler;

fun someAndroidMethod(){
    CommonHandler.init(CustomDataType)
}

The android method would get called frequently through the app, and the idea is to pass this event across to KMM for further processing ( like filtering, extracting data, and updating DB), but am unable to figure how to pass it to common KMM module. I'm a web developer who recently started KMM, so my knowledge is very limited. Kindly help, thanks in advance!


Solution

  • You can create a common wrapper for this type.

    Common code:

    expect class CustomDataType
    

    Android code:

    actual typealias CustomDataType = android.package.name.CustomDataType
    

    Sometimes it's impossible to use typealias because of different API, in this case you can store it in a property:

    actual class CustomDataType(val native: android.package.name.CustomDataType)