Kotlin学习笔记23 协程part3 lambda表达式深入 挂起函数 全局协程

本文深入探讨了Kotlin编程中的关键特性:Lambda表达式的使用,包括参数省略和函数引用;挂起函数的概念及其在协程中的应用;以及全局协程的特性,如何在程序中创建和控制它们。通过示例代码,展示了这些概念在实际编程中的实现和交互。
摘要由CSDN通过智能技术生成

参考链接

示例来自bilibili Kotlin语言深入解析 张龙老师的视频

1 lambda表达式深入

/**
 * lambda 表达式深入
 * 当函数参数是函数时 并且该函数只有一个参数 可以不传入任何参数
 * 之前讲lambda表达式时提到 当函数只有一个参数时 在调用该函数时 我们可以用it代替这个唯一参数
 * 而这个it又是可以省略的
 * 如果函数体内部没有使用it 就像是it这个参数不存在一样
 *
 */

fun main() {
    // test参数中有一个是函数 该函数不接受参数
    test(5, action = {
        println("hello")
    })

    // 当函数参数是函数时 并且该函数只有一个参数 完整格式如下
    // 在调用该函数时 我们可以用it代替这个唯一参数
    // 然后it还是是可以省略的
    test2(x=1,action = {
            it -> println("hello $it")
    })

    test2(x=1,action = {
            println("hello $it")
    })

    // 进阶版如下
    // 看起来就是我们没有输入任何参数
    test2(5, action = {
        println("hello")
    })

    // test2(5,::test)// 上面说的那种情况 不适用在函数引用上

    test(5, ::test3)
    test2(5, ::test4)
    test5(5, ::test6)

    test5(5, action = { x, y ->
        test6(x, y)
    })
}

fun test(x: Int, action: () -> Unit) {
}

fun test2(x: Int, action: (para:Int) -> Unit) {
}

fun test3() {}

fun test4(x: Int) {}

fun test5(x: Int, action: (Int, Int) -> Unit) {
    action(1, 2)
}

fun test6(x: Int, y: Int) {
    println(x + y)
}



class HelloKotlin10 {
}

2 挂起函数

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

/**
 * 挂起函数
 * 被suspend修饰的函数称为挂起函数
 * 挂起函数只能使用在协程或其他的挂起函数中
 */
fun main() = runBlocking {
    launch {
        hello()
    }
    println("welcome")
}

suspend fun hello(){
    delay(400)
    println("hello")
    world()
}
suspend fun world(){
    println("world")
}

class HelloKotlin11 {

}

3 全局协程

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 全局协程类似与守护线程
 * GlobalScope.launch启动的协程就是全局协程
 * 全局协程类似于守护线程(daemon thread) (当主线程执行完毕时 如果剩余的线程全部是守护线程 主线程会直接结束 守护线程的生命周期也会完结)
 * 使用GlobalScope启动的协程 不会保持线程的生命周期,他们就像守护线程一样
 */

fun main() {
    GlobalScope.launch {
        // 重复100次(输出I am delaying $repeatNumber 并等待400ms)
        repeat(100) { repeatNumber ->
            println("I am delaying $repeatNumber")
            delay(400)
        }
    }
    Thread.sleep(2000) // 主线程被sleep阻塞 一旦时间到达 GlobalScope创建的协程即使没有执行完毕 也会直接结束
    println("main thread down")
}

/**
输出
I am delaying 0
I am delaying 1
I am delaying 2
I am delaying 3
I am delaying 4
main thread down
 */

class HelloKotlin12 {
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值