Kotlin之let,apply,run,with等函数区别2

Kotlin之let,apply,run,with等函数区别2


以前也总结过Kotlin的一些内置函数let,apply,run,with的区别——地址,后面又增加了also,takeIf,takeUnless等函数,所以这里重新总结下,然后介绍下使用场景。

前提介绍

Kotlin和Groovy等语言一样,支持闭包(block),如果函数中最后一个参数为闭包,那么最后一个参可以不写在括号中,而写在括号后面,如果只有一个参数,括号也可以去掉。

如下所示

fun toast() {
    button.setOnClickListener({
       Toast.makeText(context, "test", Toast.LENGTH_SHORT).show()
    })
}

fun toast() {
    button.setOnClickListener {
        Toast.makeText(context, "test", Toast.LENGTH_SHORT).show()
    }
}

后面介绍的几个函数都是这样的,这样就很容理解。

repeat

repeat函数是一个单独的函数,定义如下。

/**
 * Executes the given function [action] specified number of [times].
 *
 * A zero-based index of current iteration is passed as a parameter to [action].
 */
@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0..times - 1) {
        action(index)
    }
}

通过代码很容易理解,就是循环执行多少次block中内容。

fun main(args: Array<String>) {
    repeat(3) {
        println("Hello world")
    }
}

运行结果

Hello world
Hello world
Hello world

with

with函数也是一个单独的函数,并不是Kotlin中的extension,指定的T作为闭包的receiver,使用参数中闭包的返回结果

/**
 * Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

代码示例:

fun testWith() {
    // fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f()
    with(ArrayList<String>()) {
        add("testWith")
        add("testWith")
        add("testWith")
        println("this = " + this)
    }.let { println(it) }
}
// 运行结果
// this = [testWith, testWith, testWith]
// kotlin.Unit

class文件

 public static final void testWith()
  {
    Object localObject = new ArrayList();
    ArrayList localArrayList1 = (ArrayList)localObject;
    int $i$a$1$with;
    ArrayList $receiver;
    $receiver.add("testWith");
    $receiver.add("testWith");
    $receiver.add("testWith");
    String str = "this = " + $receiver;
    System.out.println(str);
    localObject = Unit.INSTANCE;
    Unit it = (Unit)localObject;
    int $i$a$2$let;
    System.out.println(it);
  }

let

首先let()的定义是这样的,默认当前这个对象作为闭包的it参数,返回值是函数里面最后一行,或者指定return

fun <T, R> T.let(f: (T) -> R): R = f(this)

简单示例:

fun testLet(): Int {
    // fun <T, R> T.let(f: (T) -> R): R { f(this)}
    "testLet".let {
        println(it)
        println(it)
        println(it)
        return 1
    }
}
//运行结果
//testLet
//testLet
//testLet

可以看看最后生成的class文件,代码已经经过格式化了,编译器只是在我们原先的变量后面添加了let里面的内容。

public static final int testLet() {
    String str1 = "testLet";
    String it = (String)str1;
    int $i$a$1$let;
    System.out.println(it);
    System.out.println(it);
    System.out.println(it);
    return 1;
}

来个复杂一定的例子

fun testLet(): Int {
    // fun <T, R> T.let(f: (T) -> R): R { f(this)}
    "testLet".let {
        if (Random().nextBoolean()) {
            println(it)
            return 1
        } else {
            println(it)
            return 2
        }
    }
}

编译过后的class文件

public static final int testLet() {
    String str1 = "testLet";
    String it = (String)str1;
    int $i$a$1$let;
    if (new Random().nextBoolean())
    {
        System.out.println(it);
        return 1;
    }
    System.out.println(it);
    return 2;
}

apply

apply函数是这样的,调用某对象的apply函数,在函数范围内,可以任意调用该对象的任意方法,并返回该对象

/**
 * Calls the specified function [block] with `this` value as its receiver and returns `this` value.
 */
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

代码示例

fun testApply() {
    // fun <T> T.apply(f: T.() -> Unit): T { f(); return this }
    ArrayList<String>().apply {
        add("testApply")
        add("testApply")
        add("testApply")
        println("this = " + this)
    }.let { println(it) }
}

// 运行结果
// this = [testApply, testApply, testApply]
// [testApply, testApply, testApply]

编译过后的class文件

  public static final void testApply()
  {
    ArrayList localArrayList1 = new ArrayList();
    ArrayList localArrayList2 = (ArrayList)localArrayList1;
    int $i$a$1$apply;
    ArrayList $receiver;
    $receiver.add("testApply");
    $receiver.add("testApply");
    $receiver.add("testApply");
    String str = "this = " + $receiver;
    System.out.println(str);
    localArrayList1 = localArrayList1;
    ArrayList it = (ArrayList)localArrayList1;
    int $i$a$2$let;
    System.out.println(it);
  }

run

run函数和apply函数很像,只不过run函数是使用最后一行的返回,apply返回当前自己的对象。

/**
 * Calls the specified function [block] with `this` value as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}
fun <T, R> T.run(f: T.() -> R): R = f()

代码示例

fun testRun() {
    // fun <T, R> T.run(f: T.() -> R): R = f()
    "testRun".run {
        println("this = " + this)
    }.let { println(it) }
}
// 运行结果
// this = testRun
// kotlin.Unit

class文件

  public static final void testRun()
  {
    Object localObject = "testRun";
    String str1 = (String)localObject;
    int $i$a$1$run;
    String $receiver;
    String str2 = "this = " + $receiver;
    System.out.println(str2);
    localObject = Unit.INSTANCE;
    Unit it = (Unit)localObject;
    int $i$a$2$let;
    System.out.println(it);
  }

另一个Run

还有个run函数,不是extension,它的定义如下,执行block,返回block的返回

/**
 * Calls the specified function [block] and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

示例

fun main(args: Array<String>) {
    val date = run {
        Date()
    }

    println("date = $date")
}
// 运行结果
// date = Thu Jan 04 19:31:09 CST 2018

also

执行block,返回this,

/**
 * Calls the specified function [block] with `this` value as its argument and returns `this` value.
 */
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}

示例:

fun main(args: Array<String>) {
    val also = Date().also {
        println("in also time = " + it.time)
    }

    println("also = $also")
}

运行结果

in also time = 1515065830740
also = Thu Jan 04 19:37:10 CST 2018

takeIf

满足block中条件,则返回当前值,否则返回null,block的返回值Boolean类型

/**
 * Returns `this` value if it satisfies the given [predicate] or `null`, if it doesn't.
 */
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? {
    contract {
        callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
    }
    return if (predicate(this)) this else null
}

示例

fun main(args: Array<String>) {
    val date = Date().takeIf {
        // 是否在2018年元旦后
        it.after(Date(2018 - 1900, 0, 1))
    }

    println("date = $date")
}

// 运行结果
// date = Thu Jan 04 19:42:09 CST 2018

takeUnless

和takeIf相反,如不满足block中的条件,则返回当前对象,否则为null

/**
 * Returns `this` value if it _does not_ satisfy the given [predicate] or `null`, if it does.
 */
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? {
    contract {
        callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
    }
    return if (!predicate(this)) this else null
}

示例


fun main(args: Array<String>) {
    val date = Date().takeUnless {
        // 是否在2018年元旦后
        it.after(Date(2018 - 1900, 0, 1))
    }

    println("date = $date")
}
// 运行结果
// date = null

总结

怎么样,是不是看晕了,没关系,我们来总结下。

函数名 定义 block参数 闭包返回返回值 函数返回值 extension 其他
repeat fun repeat(times: Int, action: (Int) -> Unit) Unit Unit 普通函数
with fun <T, R> with(receiver: T, f: T.() -> R): R = receiver.f() 无,可以使用this Any 闭包返回 普通函数
run <R> run(block: () -> R): R Any 闭包返回 普通函数
let fun <T, R> T.let(f: (T) -> R): R it Any 闭包返回
apply fun <T> T.apply(f: T.() -> Unit): T 无,可以使用this Unit this
run fun <T, R> T.run(f: T.() -> R): R 无,可以使用this Any 闭包返回
also fun <T> T.also(block: (T) -> Unit): T it Unit this
takeIF fun <T> T.takeIf(predicate: (T) -> Boolean): T? it Boolean this 或 null 闭包返回类型必须是Boolean
takeUnless fun <T> T.takeUnless(predicate: (T) -> Boolean): T? it Boolean this 或 null 闭包返回类型必须是Boolean

示例

上面就是本人所理解的,最后再给个整体示例。

定义一个结构体

class User {
    var id: Int = 0
    var name: String? = null
    var hobbies: List<String>? = null

    override fun toString(): String {
        return "User(id=$id, name=$name, hobbies=$hobbies)"
    }
}

普通的赋值语句这样就可以了

var user = User()
user.id = 1
user.name = "test1"
user.hobbies = listOf("aa", "bb", "cc")
println("user = $user")

如果使用let,apply,run,with可以这样,let和also是需要it的,其他的默认使用this。

user.let {
    it.id = 2
    it.name = "test2"
    it.hobbies = listOf("aa", "bb", "cc")
}
println("user = $user")

user.also {
    it.id = 3
    it.name = "test3"
    it.hobbies = listOf("aa", "bb", "cc")
}
println("user = $user")

user.apply {
    id = 2
    name = "test2"
    hobbies = listOf("aa", "bb", "cc")
    Date()
}
println("user = $user")

user.run {
    id = 3
    name = "test3"
    hobbies = listOf("aa", "bb", "cc")
    Date()
}
println("user = $user")

with(user) {
    id = 4
    name = "test4"
    hobbies = listOf("aa", "bb", "cc")
    Date()
}
println("user = $user")

再举一个例子,一个http的response结构体。

class Resp<T> {
    var code: Int = 0
    var body: T? = null
    var errorMessage: String? = null

    fun isSuccess(): Boolean = code == 200

    override fun toString(): String {
        return "Resp(code=$code, body=$body, errorMessage=$errorMessage)"
    }
}

在处理网络数据的时候,需要各种判断,比如。

fun main(args: Array<String>) {
    var resp: Resp<String>? = Resp()

    if (resp != null) {
        if (resp.isSuccess()) {
            // do success
            println(resp.body)
        } else {
            // do fail 
            println(resp.errorMessage)
        }
    }
}

当然也可以用apply,let,run等函数。

fun main(args: Array<String>) {
    var resp: Resp<String>? = Resp()

//    if (resp != null) {
//        if (resp.isSuccess()) {
//            // do success
//            println(resp.body)
//        } else {
//            println(resp.errorMessage)
//        }
//    }

    resp?.run {
        if (isSuccess()) {
            // do success
            println(resp.body)
        } else {
            println(resp.errorMessage)
        }
    }

    resp?.apply {
        if (isSuccess()) {
            // do success
            println(resp.body)
        } else {
            println(resp.errorMessage)
        }
    }

    resp?.let {
        if (it.isSuccess()) {
            // do success
            println(it.body)
        } else {
            println(it.errorMessage)
        }
    }

    resp?.also {
        if (it.isSuccess()) {
            // do success
            println(it.body)
        } else {
            println(it.errorMessage)
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容