刚好有一个地方是如果变量不为空就执行什么什么
翻kotlin实战pdf,发现了let函数
下面开始copy大法
kotlin实战 let函数
kotlin实战 let函数

kotlin实战 let函数
kotlin实战 let函数
我之前使用apply函数来做这个事情的,因为前面我有很多new一个对象的地方使用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
}

而let的源码是


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

可以看到apply返回this,let返回block的返回值

相关文章:

  • 2021-11-12
  • 2021-06-24
  • 2021-04-11
  • 2021-05-15
  • 2021-09-08
  • 2021-10-19
  • 2021-09-27
  • 2021-07-15
猜你喜欢
  • 2022-12-23
  • 2021-04-15
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
  • 2021-09-08
  • 2022-01-12
相关资源
相似解决方案