1、takeIf的源码
/**
* Returns `this` value if it satisfies the given [predicate] or `null`, if it doesn't.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#takeif-and-takeunless).
*/
@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
}
2、takeUnless的源码
/**
* Returns `this` value if it _does not_ satisfy the given [predicate] or `null`, if it does.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#takeif-and-takeunless).
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? {
contract {
callsInPlace(predicate, InvocationKind.EXACTLY_ONCE)
}
return if (!predicate(this)) this else null
}
3、实际应用中的用法
fun uotation(params: QuotationParam, companyCode: String?) = coroutineScope {
val exchangeDate = LocalDate.now() //前端没有传递参数,默认为调用当天的汇率
val exchangeDto = companyCode?.takeUnless { it.isBlank() }
?.let { company ->
XXX.getExchangeWithCompanyCode(company, exchangeDate).data
} ?: XXX.getExchangeWithCurrency(“RMB”, exchangeDate).data
}
4、takeIf的使用总结
param?.takeIf{it.isBlank()}?.let{//it.isBlank()成立要做的事情}?:{
//it.isBlank()不成立要做的事情}
5、takeUnless的使用
param?.takeUnless{it.isBlank()}?.let{ //it.isBlank()不成立要做的事情}?:{//it.isBlank()成立要做的事情}