Thread
#multiplatform
    a

    albertosh

    2 years ago
    Hi Anyone tried to typealias an expected 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
    expect class Wrapper<T: Any?>
    Working Kotlin for JVM code
    actual typealias Wrapper<T> = CompletableFuture<T>
    Not working Kotlin for JS code
    actual typealias Wrapper<T> = Promise<T>
    Compiler claims that
    Aliased class should not have type parameters with declaration-site variance
    Any clue?
    Big Chungus

    Big Chungus

    2 years ago
    +
    russhwolf

    russhwolf

    2 years ago
    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

    albertosh

    2 years ago
    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
    internal expect fun asyncWrapper(body: suspend () -> ExperimentJournal?): AsyncWrapper<ExperimentJournal?>
    
    expect class AsyncWrapper<T: Any?>
    JVM code
    internal actual fun asyncWrapper(body: suspend () -> MyClass?): AsyncWrapper<MyClass?> =
            GlobalScope.future {
                body()
            }
    
    actual typealias AsyncWrapper<T> = CompletableFuture<T>
    JS 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