ForteScarlet / kotlin-suspend-transform-compiler-plugin

A Kotlin compiler plugin for transforming suspend functions to platform-compatible non-suspend functions, such as the JVM Blocking API and CompletableFuture or JS Promise, etc. 🐱
MIT License
36 stars 3 forks source link

针对 CoroutineScope 类型的参数的填充优化 #32

Closed ForteScarlet closed 1 year ago

ForteScarlet commented 1 year ago

当转换函数中存在 CoroutineScope 类型的参数时,会根据当前 receiver 尝试 将其填充至此参数。

e.g.

transform function:

public fun <T> runInAsync(
    block: suspend () -> T,
    // A `CoroutineScope` parameter
    scope: CoroutineScope = DefaultCoroutineScope
): CompletableFuture<T> {
    return scope.future { block() }
}

source:

abstract class Foo : CoroutineScope {
    @JvmAsync
    abstract suspend fun stringToInt(value: String): Int
} 

generated:

abstract class Foo : CoroutineScope {
    @JvmAsync
    abstract suspend fun stringToInt(value: String): Int

    fun stringToIntAsync(value: String): Int = 
        runInAsync({ stringToInt(value) }, this /* Use 'this' as CoroutineScope */)

}

and nullable support (推荐) .

transform function:

public fun <T> runInAsync(
    block: suspend () -> T,
    // A `CoroutineScope` parameter
    scope: CoroutineScope? = null
): CompletableFuture<T> {
    return(scope ?: DefaultCoroutineScope).future { block() }
}

source:

abstract class Foo { // not `CoroutineScope`
    @JvmAsync
    abstract suspend fun stringToInt(value: String): Int
} 

generated:

abstract class Foo {
    @JvmAsync
    abstract suspend fun stringToInt(value: String): Int

    fun stringToIntAsync(value: String): Int = 
        runInAsync({ stringToInt(value) }, this as? CoroutineScope /* Try to use 'this' as CoroutineScope */)

}

第二种方式在接口/抽象类中使用会更加有效,因为这可以使其实现的子类不再必须显示重新标记转化函数即可享受到 CoroutineScope 的转化