Hi Anyone tried to typealias an `expect`ed class? ...
# multiplatform
a
Hi Anyone tried to typealias an `expect`ed class? Looks like I can do it for the JVM but not for JS. The aim is to provide a “platform native” output for some functions so they can be used from Java/Js My common code
Copy code
expect class Wrapper<T: Any?>
Working Kotlin for JVM code
Copy code
actual typealias Wrapper<T> = CompletableFuture<T>
Not working Kotlin for JS code
Copy code
actual typealias Wrapper<T> = Promise<T>
Compiler claims that
Aliased class should not have type parameters with declaration-site variance
Any clue?
b
+
r
typealias needs to be an exact signature match. Promise is declared as
open class Promise<out T>
and the
out
and
open
are missing in your
expect
statement.
a
I see In the end, I ended up wiring things manually. Not as nice & clean as just typealiasing stuff but works as well Common code
Copy code
internal expect fun asyncWrapper(body: suspend () -> ExperimentJournal?): AsyncWrapper<ExperimentJournal?>

expect class AsyncWrapper<T: Any?>
JVM code
Copy code
internal actual fun asyncWrapper(body: suspend () -> MyClass?): AsyncWrapper<MyClass?> =
        GlobalScope.future {
            body()
        }

actual typealias AsyncWrapper<T> = CompletableFuture<T>
JS code
Copy code
internal actual fun asyncWrapper(body: suspend () -> MyClass?): AsyncWrapper<MyClass?> {
    return AsyncWrapper(GlobalScope.promise {
        body()
    })
}

actual class AsyncWrapper<T : Any?>(
        internal val promise: Promise<T>
) {
    @JsName("then")
    fun <S> then(onFulfilled: ((T) -> S)?, onRejected: ((Throwable) -> S)?): Promise<S> = promise.then(onFulfilled, onRejected)

    @JsName("catch")
    fun <S> catch(onRejected: (Throwable) -> S): Promise<S> = promise.catch(onRejected)
}

suspend fun AsyncWrapper<Any>.await() = promise.await()
I don’t actually like much the JS one. I tried to extend Promise but I kept getting some undefined related errors, so I had to replicate some code. In the end, it’s not that much code to replicate
Main idea is that in JVM it will be handled as
CompletableFuture
and in JS as
Promise
It’s just an “output” type of the library, so it will not be used internally