Kotlin 协程中的“+”?

use*_*558 5 operator-overloading coroutine kotlin kotlinx.coroutines

这是Kotlin 协程通过显式作业取消的示例代码:

fun main(args: Array<String>) = runBlocking<Unit> {
    val job = Job() // create a job object to manage our lifecycle

    // now launch ten coroutines for a demo, each working for a different time
    val coroutines = List(10) { i ->
        // they are all children of our job object
        launch(coroutineContext + job) { // we use the context of main runBlocking thread, but with our own job object
            delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc
            println("Coroutine $i is done")
        }
    }
    println("Launched ${coroutines.size} coroutines")
    delay(500L) // delay for half a second
    println("Cancelling the job!")
    job.cancelAndJoin() // cancel all our coroutines and wait for all of them to complete
}
Run Code Online (Sandbox Code Playgroud)

+对表达感到困惑coroutineContext + job

它在做什么?它是运算符覆盖吗?

s1m*_*nw1 5

这是运算符重载的一个例子。以下显示了方法的文档CoroutineContext::plus

open operator fun plus(context: CoroutineContext): CoroutineContext
Run Code Online (Sandbox Code Playgroud)

返回包含来自此上下文的元素和来自其他上下文的元素的上下文。删除此上下文中与另一个上下文中具有相同键的元素。

它基本上是两个上下文的合并。

  • 这里值得注意的是,您始终可以通过 Ctrl+单击(在 Mac 上为 Cmd+单击)在 IDEA 代码中的“+”符号上导航到相应的方法以查看其文档。 (3认同)