kotlin埋点_使用Kotlin高效地开发Android App(二)

继上一篇文章介绍了项目中所使用的Kotlin特性,本文继续整理当前项目所用到的特性。

一.apply 函数 和 run 函数

with、apply、run函数都是Kotlin标准库中的函数。with在第一篇文章中已经介绍过。

1.1 apply函数

apply函数是指在函数块内可以通过 this 指代该对象,返回值为该对象自己。在链式调用中,可以考虑使用它来不破坏链式。

/**

* Calls the specified function [block] with `this` value as its receiver and returns `this` value.

*/

@kotlin.internal.InlineOnly

public inline fun T.apply(block: T.() -> Unit): T {

contract {

callsInPlace(block, InvocationKind.EXACTLY_ONCE)

}

block()

return this

}

举个例子:

/**

* Created by tony on 2018/4/26.

*/

object Test {

@JvmStatic

fun main(args: Array) {

val result ="Hello".apply {

println(this+" World")

this+" World"

}

println(result)

}

}

执行结果:

Hello World

Hello

第一个字符串是在闭包中打印的,第二个字符串是result的结果,它仍然是“Hello”。

1.2 run函数

run函数类似于apply函数,但是run函数返回的是最后一行的值。

/**

* Calls the specified function [block] with `this` value as its receiver and returns its result.

*/

@kotlin.internal.InlineOnly

public inline fun T.run(block: T.() -> R): R {

contract {

callsInPlace(block, InvocationKind.EXACTLY_ONCE)

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值