Kotlin 标准库中run、let、also、apply、with函数的用法和区别

345 阅读1分钟

run 函数

定义


inline fun <R> run(block: () -> R): R         //1
Calls the specified function block and returns its result.


inline fun <T, R> T.run(block: T.() -> R): R  //2
Calls the specified function block with this value as its receiver and returns its result.

第一种使用:直接使用run函数返回其结果(最后一行的结果)


fun runTest() {
    val a = run {
        "abc"
        1
    }
    val b = run {
        1
        2
        "abc"
    }
    println(a)
    println(b)
}

打印结果:

1

abc

第二种使用:调用某个对象(该对象作为接收者)的run函数并返回结果


fun runTestWithT() {
    val a = 1.run {
        "$this 和 abc"
    }
    println(a)
}  

打印结果:

1 和 abc

let 函数

定义


inline fun <T, R> T.let(block: (T) -> R): R
Calls the specified function block with this value as its argument and returns its result.

使用:调用某个对象(该对象作为函数的参数)的let的函数并返回结果


fun letTest() {
    val let = "abc".let {
        println(it)
        1
    }
    println(let)
}

打印结果:

abc

1

also 函数

定义


inline fun <T> T.also(block: (T) -> Unit): T
Calls the specified function block with this value as its argument and returns this value.

使用: 调用某一对象的also 函数(该对象作为函数参数)并返回改对象


fun alsoTest() {
    val also = "abc".also {
        println(it)
    }
    println(also)
}

打印结果:

abc
abc

apply 函数

定义


inline fun <T> T.apply(block: T.() -> Unit): T
Calls the specified function block with this value as its receiver and returns this value.

使用:调用对象(该对象作为接收者)的apply函数并返回该对象


fun applyTest(){
    val apply ="abc".apply {
        println(this)
    }
    println(apply)
}

打印结果:

abc

abc

with 函数

定义


inline fun <T, R> with(receiver: T, block: T.() -> R): R
Calls the specified function block with the given receiver as its receiver and returns its result.

使用:使用给定接收器作为接收器调用with函数并返回其结果


fun withTest() {
    val with = with("abc") {
        println(this)
        1111
    }
    println(with)
}

打印结果:

abc
1111

with 函数的使用形式与其他几个函数的类型不一样

with 函数重要的一个作用是使用它实现构建者模式

举个例子


class Student(builder: Builder) {

    var name: String = ""
    var age = 1

    init {
        name = builder.name
        age = builder.age
    }

    class Builder {
        var name: String = ""
        var age: Int = 0
        fun builder(): Student = Student(this)
    }
}

使用with函数构建:


fun withTest() {

    val student = with(Student.Builder()) {
        this.age = 18
        this.name = "marry"
        builder()
    }
    println("name: ${student.name},age:${student.age}")
}

打印结果:


name: marry,age:18

看了上面的几个简单的使用,我们可能就能从几个函数的定义可以看出他们区别:

从返回结果不同来看

  • 返回其他结果runletwith

  • 返回自身结果alsoapply

从对象调用的作用来看

  • 调用者作为参数letalso

  • 调用者作为接受者runwithapply

参考:kotlinlang.org/api/latest/…