kotlin function return function

kotlin function return function

https://blog.csdn.net/zhangphil/category_12220817.htmlhttps://blog.csdn.net/zhangphil/category_12220817.html

Example 1:

// func返回匿名函数
fun func(msg: String): (String, Int) -> String {
    println("func函数 msg:$msg")

    // 返回匿名函数
    return { name: String, age: Int ->
        "匿名函数:name:$name,age:$age,msg:$msg"
    }
}

fun main(args: Array<String>) {
    // foo是func函数的返回值,这个返回值是函数
    val foo = func("kotlin")

    // foo是匿名函数
    println(foo("zhangphil", 18))
}

output:

func function msg:kotlin
Anonymous function: name:zhangphil,age:18,msg:kotlin


Example 2: Calculate 2 * (3+4)

fun math(c: Int): (Int, Int) -> Int {
    return { a: Int, b: Int -> (a + b) * c }
}

fun main(args: Array<String>) {
    val foo = math(2)

    // foo是匿名函数
    println(foo(3, 4))
}

output:

14

Kotlin coroutines, thread switching, function method entrustment_zhangphil's blog-CSDN blog runBlocking internally starts 3 coroutines to do time-consuming operations, you can see from the output that 3 coroutines are cross-concurrently executed, and runBlocking will wait until 3 coroutines Exit after the execution is completed, and the output results have a clear sequence. General programming techniques, for example, in Android, suppose a function is implemented in the main thread, but this function is a time-consuming operation, there is no doubt that the implementation of this function needs to be cut into a non-main thread for operation, then you can design a A managed function that does dirty work in the managed function, and throws the result to the main thread after the processing is completed. Result 1-a: 5 - tid: 22. Result 1-b: 5 - tid: 24. Result 2-a: 9 - tid: 22. https://zhangphil.blog.csdn.net/article/details/130161705

Guess you like

Origin blog.csdn.net/zhangphil/article/details/129222840