rickclephas / KMP-NativeCoroutines

Library to use Kotlin Coroutines from Swift code in KMP apps
MIT License
1.06k stars 31 forks source link

Generic types with @NativeCoroutines #180

Closed daniellfalcao closed 4 months ago

daniellfalcao commented 4 months ago

I'm trying to create a generic function with the following signature:

actual class OperationResult<T> actual constructor(private val block: suspend () -> T) {

    @NativeCoroutines
    suspend fun getResult(): T = block()
}

When I call asyncFunction from swift where the return type of the code is an OperationResult<String>, for example, the return of .getResult() becomes Any. Is there anything that can be done to avoid casting on the Swift side?

Ex: Screenshot 2024-06-25 at 18 05 04

daniellfalcao commented 4 months ago

Without using the annotation, Swift can resolve the type correctly.

Screenshot 2024-06-25 at 18 40 35

rickclephas commented 4 months ago

This is an unfortunate limitation of the KSP usage and Kotlin-Swift interop. In this case, the plugin will generate a generic extension, which is unfortunately not supported. These generics are lost in translation to Swift.

Since it seems your code is in an Apple/iOS source set, you could manually create the necessary code inside the class:

import com.rickclephas.kmp.nativecoroutines.nativeSuspend
import kotlin.native.ObjCName

@ObjCName(name = "getResult")
fun getResultNative() = nativeSuspend { getResult() }

Just annotate your original function with @HiddenFromObjC to prevent name conflicts.

daniellfalcao commented 4 months ago

It works!!! Thank you!

Screenshot 2024-06-26 at 08 07 43