美文网首页
Kotlin let,run,with,also,apply 函

Kotlin let,run,with,also,apply 函

作者: gooddaytoyou | 来源:发表于2019-06-05 14:35 被阅读0次

let

  • 是扩展函数;
  • 作为扩展函数,把自己作为参数传递进去,(T);
  • 可以在作用域范围内使用it作为引用;
  • 返回不同类型的值。
public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

run

  • 是扩展函数;
  • 作为扩展函数调用block: T.()
  • 所有的范围内,T可以被称为this;
  • 返回不同类型的值。
public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

also

  • 是扩展函数;
  • 作为扩展函数,把自己作为参数传递进去,(T);
  • 可以在作用域范围内使用it作为引用;
  • 返回T本身即this。
public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}

with

  • 不是扩展函数;
  • 所有的范围内,T可以被称为this;
  • 返回不同类型的值。
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}

apply

  • 是扩展函数;
  • 作为扩展函数调用block: T.()
  • 所有的范围内,T可以被称为this;
  • 返回T本身即this。
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

相关文章

网友评论

      本文标题:Kotlin let,run,with,also,apply 函

      本文链接:https://www.haomeiwen.com/subject/bozjxctx.html