Kotlin 中的 appy和with方法
apply
apply:Calls the specified function block with this value as its receiver and returns this value.
實作:
public inline fun <T> T.apply(block: T.() -> Unit): T {
block();
return this
}
apply為高階函數,它接受一個參數block,類型為 T.() -> Unit ( function-with-receiver)
在apply的函數體内,調用了傳入的block這個函數,然後傳回調用apply函數的對象執行個體。
//調用方法, 省去了 this
fun getDeveloper(): Developer {
return Developer().apply {
developerName = "Amit Shekhar"
developerAge = 22
}
}
with
Calls the specified function block with the given receiver as its receiver and returns its result.
它的實作代碼也隻有一行
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
with為高階函數,接收兩個參數:receiver,類型為T,block 類型為 T.() -> R,為 function-with-receiver type,隻能被T類型的對象調用.
同樣,在block方法體内,可以通過this來調用到receiver。
with傳回的類型為R,和block的傳回類型相同
fun getPersonFromDeveloper(developer: Developer): Person {
return with(developer) {
Person(developerName, developerAge)
}
}