/**
* 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)
}
data class Chicken(var name: String, var weight: Int)
fun main() {
val chicken = Chicken("小母鸡", 30)
val chickenNew = chicken.apply {
println("原来的名字:${this.name}")
this.name = "小花鸡"
}
println("现在的名字:${chickenNew.name}")
}
//输出结果
原来的名字:小母鸡
现在的名字:小花鸡
5、函数:also
源码:
/**
* 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
}
data class Chicken(var name: String, var weight: Int)
fun main() {
val chicken = Chicken("小母鸡", 30)
val chickenAlso = chicken.also { chicken1: Chicken ->
println("原来的重量:${chicken1.weight}")
chicken1.weight = 40
}
println("现在的重量:${chickenAlso.weight}")
}
//输出结果
原来的重量:30
现在的重量:40
源码:
/**
* Calls the specified function [block] with `this` value as its argument and returns `this` value.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
6、函数:takeIf
//源码:
/**
* Returns `this` value if it satisfies the given [predicate] or `null`, if it doesn't.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (predicate(this)) this else null
}
data class Cat(var name: String, var weight: Int)
fun main() {
val cat = Cat("小花", 10)
val cat1 = cat.takeIf { catP: Cat ->
catP.weight > 10
}
val cat12 = cat.takeUnless {
it.weight > 10
}
println("cat1=$cat1")
println("cat12=$cat12")
}
//输出结果
cat1=null
cat12=Cat(name=小花, weight=10)
8、函数:with
//源码
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
data class Cat(var name: String, var weight: Int)
fun main() {
val cat = Cat("小花", 10)
val result=with(cat){
this.name="小白"
this.weight=11
1+1
}
println("cat.name=${cat.name}")
println("cat.weight=${cat.weight}")
println("result=$result")
}
//输出结果
cat.name=小白
cat.weight=11
result=2
9、总结
这些作用域函数的作用还是具有很多的开放性,你可以用他们来做很多逻辑赋值操作。这就要看你的发挥了。
data class Cat(var name: String, var weight: Int)
fun main() {
val cat = Cat("小花", 10)
val newName = cat.also {
it.name = it.name + "+1"
}.takeIf {
it.weight <= 10
}?.apply {
this.name = this.name + "+2"
}?.run {
[email protected] name + "+3"
}
println("newName=$newName")
}
//输出结果
newName=小花+1+2+3