Skip to content

Conversation

@ForteScarlet
Copy link
Owner

@ForteScarlet ForteScarlet commented Aug 9, 2023

当转换函数中存在 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 的转化

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants