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)
}
网友评论