判断空

省略

it/this

上下文对象 返回值  
let   it Lambda result  
with   this Lambda result  
run this Lambda result

=let + with

  可以省略this,也可以判断空

apply   this 上下文对象(自身)

val person1 = Person("tom")
Person(name = "洛城夜雨").apply {
        age = 26
        person1.age = 28
        city = "洛阳"
        print(person1)
}
可以省略this,但是用以混乱

also   it

上下文对象(自身)

 

跟apply差不多,

好处是

1.函数内外的this含义一样。

    apply要写this@MainActivity

2.可以用it,也可以自定义上下文名称

Person(name = "汤姆").also { tom -> print(tom)

 }

           

在这里插入图片描述

函数使用场景

很多人接触到作用域函数的时候,最头疼的问题不是不会用,而是不知道如何选择合适的作用域函数。之所以出现这种情况,是因为其实作用域函数在多数情况下是可以互换的,因此官方文档也给我们推荐了各个函数常见的使用场景。

函数选择

栗子代码

package com.zy

val students = run {
    // 顶级初始化
    mutableListOf<Person>().apply {
        add(Person("Abel"))
        add(Person("Ben"))
        add(Person("Colin"))
        add(Person("Denny"))
        add(Person("Frank"))
    }
}

fun main() {
    // 链式调用
    students.apply {
        // 对象配置
        add(Person(name = "Cecil", city = "LuoYang"))
    }.filter {
        it.name.startsWith("C")
    }.also {
        // 附加操作
        println("名字以字母C开头的学生人数为${it.size}")
    }.forEach { person ->
        val separator = if (person.city == null) "\n" else ""
        print("name = ${person.name} $separator")
        person.city?.let {
            // 空检查
            print(", city = ${it.toLowerCase()}")
        }
    }
    println()
    students.last().let { lastStudent ->
        // 上下文对象以lastStudent为参数名,作为局部范围中的变量引入
        val name = if (lastStudent.name.length < 10) "[${lastStudent.name}]" else lastStudent.name
        println("列表中最后一个学生是:$name")
    }
    students.run {
        // 对象配置 + 结果运算
        add(Person(name = "Mark", city = "Boston"))
        "students.size = $size"
    }.also(::println)

    // 调用列表中最后一个学生的 sayHello 和 introduceYourself 方法
    with(students.last()){
        sayHello()
        introduceYourself()
    }
}

class Person(val name: String, var city: String? = null) {

    fun sayHello() {
        println("Hello everyone!")
    }

    fun introduceYourself() {
        println("My name is $name and I'm from $city.")
    }
}

 

参考

Kotlin スコープ関数 用途まとめ
https://qiita.com/ngsw_taro/items/d29e3080d9fc8a38691e#with

玩转kotlin的作用域函数
https://blog.csdn.net/lyzhou1107/article/details/100575097


kotlin常见函数let,with,run,apply,also的使用
https://blog.csdn.net/qq_15988951/article/details/104918297

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐