Is there any solution to `expect` a function with ...
# multiplatform
j
Is there any solution to
expect
a function with different returns types in the actual implementations? I have
suspend fun makeRequest(): Unit
for my native target, but Kotlin doesn’t allow to apply
@JsExport
due to the suspend keyword so I’ve created
fun makeRequest(): Promise<Unit>
for the JS target. However, due to the different return types I can’t find any way to
expect
in my common code the
makeRequest
function. Is there any workaround?
m
You won't be able to have a different signature for
expect
functions since expect defines a strict interface for you to use from common code without caring about platform which the compiler can then swap out for the platforms implementation without any extra adapting. Since you need to decide how to turn a promise into a suspend call the compiler won't be able to handle the different signatures. It sounds like what you want to do is have a public class that offers a suspend function for kotlin code to call and a promise for Js code to call. In general our team tends to advise avoiding expect in all but very simple situations, and almost never in the public interface of our shared code.
What I would recommend and that I've done in the past is to have your
RequestService
class with
suspend fun makeRequest()
that you can call internally and from nonshared kotlin code. Then you can write wrapper classes in each of your other sourceSets that serve as adapters for
RequestService
specific to how each platform wants to consume your async api. So converting it to Promise for Js, making it a callback for swift/java etc. There's a helper function I think as an extension on coroutinesScope
Copy code
fun makeRequestPromise(): Promise<Unit> = scope.promise { service.makeRequest() }
j
Yeah, that was the only option I had in mind but I was not sure about it. Now I can go for it without any doubt or fear of missing something, thank you!
In general our team tends to advise avoiding expect in all but very simple situations, and almost never in the public interface of our shared code.
Yeah I see now how it can bring issues.
m
Yea our usual advice is use interfaces instead until you hit something where you can't, then maybe use expect in that case