美文网首页
also()、takeIf()

also()、takeIf()

作者: 江南_烟雨 | 来源:发表于2017-12-28 09:51 被阅读0次

also 就像 apply :它接受接收者、做一些动作、并返回该接收者。二者区别是在 apply
内部的代码块中接收者是 this , 而在 also 内部的代码块中是 it 。

class Block {
lateinit var content: String
}
//sampleStart
fun Block.copy() = Block().also {
it.content = this.content
}
//sampleEnd
// 使用“apply”代替
fun Block.copy1() = Block().apply {
this.content = this@copy1.content
}
fun main(args: Array<String>) {
val block = Block().apply { content = "content" }
val copy = block.copy()
println("Testing the content was copied:")
println(block.content == copy.content)
}

相关文章

网友评论

      本文标题:also()、takeIf()

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