1、takeIf的源码
@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的源码
@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()成立要做的事情}
|