Kotlin 如何使用let(或apply等)检查2个条件
有没有更惯用的方法来写下面的内容Kotlin 如何使用let(或apply等)检查2个条件,kotlin,Kotlin,有没有更惯用的方法来写下面的内容 foo?.let{ if(!foo.isBlank()) { bar?.let { if(!bar.isBlank()) { println("foo and bar both valid strings") } } } } 基本上,这两个字符串都应该是非null和非空
foo?.let{
if(!foo.isBlank()) {
bar?.let {
if(!bar.isBlank()) {
println("foo and bar both valid strings")
}
}
}
}
基本上,这两个字符串都应该是非null和非空的,我想知道如果(foo.isNullOrEmpty&!bar.isNullOrEmpty)使用这个
fun <T, R, S> biLet(lhs: T, rhs: R, block: (T, R) -> S): S? = if (lhs != null && rhs != null) block(lhs, rhs) else null
编辑:字符串的变量
fun <T: CharSequence?, S> biLet(lhs: T, rhs: T, block: (T, T) -> S): S? =
if (lhs.isNotNullOrBlank() && rhs.isNotNullOrBlank()) block(lhs, rhs) else null
fun-biLet(左:T,右:T,block:(T,T)->S:S=
if(lhs.isNotNullOrBlank()&&rhs.isNotNullOrBlank())块(lhs,rhs)else null
使用lambda声明一个扩展函数,如:
inline fun String.ifNotEmpty(bar: String, function: () -> Unit) {
if (this.isNotEmpty() && bar.isNotEmpty()) {
function.invoke()
}
}
并将其用作:
val foo = "foo-value"
val bar = "bar-value"
foo.ifNotEmpty(bar) {
println("foo and bar both valid strings")
}
您可以使用
sequenceOf
和none
:
if (sequenceOf(foo, bar).none { it.isNullOrBlank() }) {
println("foo and bar both valid strings")
}
为了改进@Francesc答案,我创建了一个nLet版本
fun <S> nLet(vararg ts: Any?, block: (Array<out Any?>) -> S): S? =
if (ts.none { when (it) { is String -> it.isNullOrEmpty() else -> it == null } }) block(ts) else null
这就是我使用的:
fun <P1, P2, R> nLet(p1: P1?, p2: P2?, block: (P1, P2) -> R?): R? =
p1?.let { p2?.let { block(p1, p2) } }
如果需要更多参数,请添加更多具有更多
p
的nLet函数。您也可以将其用于任意数量的参数:
fun <P, R> nLet(vararg ts: P?, block: (Array<out P?>) -> R): R? =
ts.takeIf { it.none { it == null } }?.let { block(it) }
这是可行的,但是f
、b
和d
将具有可空类型,即使它们不能为空
(可能有一个聪明的方法来解决这个问题……范围函数在这里帮不了你。Kotlin鼓励我们首先选择简洁的表单:,因此,
isNullOrEmpty
是最佳选择。但是如果检查只针对null
我可以直接使用let
,对吗?你仍然需要链接两个let,对于biLet,它是一个单独的调用。但是在biLet
实现中,因为它是泛型的,所以我无法检查是否为空。所以在块中
我需要添加它。是的,这是一个空安全函数。您可以创建一个检查空字符串的变量,我将更新响应。很好!我想知道,如果bar
不是String
的话,这是否可行,如果bar
是CharSequence?
的一个子类型,它就会起作用。否则,您将无法在it
上调用isNullOrBlank()。It投诉isNullOrBlank
fun <P1, P2, R> nLet(p1: P1?, p2: P2?, block: (P1, P2) -> R?): R? =
p1?.let { p2?.let { block(p1, p2) } }
nLet(foo, bar) { f, b -> doStuff(f, b) }
fun <P, R> nLet(vararg ts: P?, block: (Array<out P?>) -> R): R? =
ts.takeIf { it.none { it == null } }?.let { block(it) }
nLet(foo, bar, dog) { (f, b, d) -> doStuff(f, b, d) }