Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 9, 2023

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.

1 participant