Kotlin 的多变量 let

有没有什么方法可以在 kotlin 中链接多个可空变量的多个 let?

fun example(first: String?, second: String?) {
first?.let {
second?.let {
// Do something just if both are != null
}
}
}

我是说,就像这样:

fun example(first: String?, second: String?) {
first?.let && second?.let {
// Do something just if both are != null
}
}
69583 次浏览

您可以为此编写自己的函数:

 fun <T, U, R> Pair<T?, U?>.biLet(body: (T, U) -> R): R? {
val first = first
val second = second
if (first != null && second != null) {
return body(first, second)
}
return null
}


(first to second).biLet { first, second ->
// body
}

你可以创建一个 arrayIfNoNulls函数:

fun <T : Any> arrayIfNoNulls(vararg elements: T?): Array<T>? {
if (null in elements) {
return null
}
@Suppress("UNCHECKED_CAST")
return elements as Array<T>
}

然后,您可以使用它为 let的一个可变数目的值:

fun example(first: String?, second: String?) {
arrayIfNoNulls(first, second)?.let { (first, second) ->
// Do something if each element is not null
}
}

如果你已经有一个数组,你可以创建一个 takeIfNoNulls函数(灵感来自于 takeIfrequireNoNulls) :

fun <T : Any> Array<T?>.takeIfNoNulls(): Array<T>? {
if (null in this) {
return null
}
@Suppress("UNCHECKED_CAST")
return this as Array<T>
}

例如:

array?.takeIfNoNulls()?.let { (first, second) ->
// Do something if each element is not null
}

这里有一些变化,取决于什么样式你将要使用,如果你有一切相同或不同的类型,如果列表未知的项目数量..。

混合类型,所有类型都不能为空,以计算新值

对于混合类型,您可以为每个参数计数构建一系列函数,这些函数看起来可能很傻,但对于混合类型可以很好地工作:

inline fun <T1: Any, T2: Any, R: Any> safeLet(p1: T1?, p2: T2?, block: (T1, T2)->R?): R? {
return if (p1 != null && p2 != null) block(p1, p2) else null
}
inline fun <T1: Any, T2: Any, T3: Any, R: Any> safeLet(p1: T1?, p2: T2?, p3: T3?, block: (T1, T2, T3)->R?): R? {
return if (p1 != null && p2 != null && p3 != null) block(p1, p2, p3) else null
}
inline fun <T1: Any, T2: Any, T3: Any, T4: Any, R: Any> safeLet(p1: T1?, p2: T2?, p3: T3?, p4: T4?, block: (T1, T2, T3, T4)->R?): R? {
return if (p1 != null && p2 != null && p3 != null && p4 != null) block(p1, p2, p3, p4) else null
}
inline fun <T1: Any, T2: Any, T3: Any, T4: Any, T5: Any, R: Any> safeLet(p1: T1?, p2: T2?, p3: T3?, p4: T4?, p5: T5?, block: (T1, T2, T3, T4, T5)->R?): R? {
return if (p1 != null && p2 != null && p3 != null && p4 != null && p5 != null) block(p1, p2, p3, p4, p5) else null
}
// ...keep going up to the parameter count you care about

示例用法:

val risk = safeLet(person.name, person.age) { name, age ->
// do something
}

当 list 没有空项时执行代码块

这里有两种风格,第一种是在列表中有所有非空项时执行代码块,第二种是在列表中至少有一个非空项时执行相同的代码块。这两种情况都将非空项的列表传递给代码块:

职能:

fun <T: Any, R: Any> Collection<T?>.whenAllNotNull(block: (List<T>)->R) {
if (this.all { it != null }) {
block(this.filterNotNull()) // or do unsafe cast to non null collection
}
}


fun <T: Any, R: Any> Collection<T?>.whenAnyNotNull(block: (List<T>)->R) {
if (this.any { it != null }) {
block(this.filterNotNull())
}
}

示例用法:

listOf("something", "else", "matters").whenAllNotNull {
println(it.joinToString(" "))
} // output "something else matters"


listOf("something", null, "matters").whenAllNotNull {
println(it.joinToString(" "))
} // no output


listOf("something", null, "matters").whenAnyNotNull {
println(it.joinToString(" "))
} // output "something matters"

稍作修改,让函数接收项目列表并执行相同的操作:

fun <T: Any, R: Any> whenAllNotNull(vararg options: T?, block: (List<T>)->R) {
if (options.all { it != null }) {
block(options.filterNotNull()) // or do unsafe cast to non null collection
}
}


fun <T: Any, R: Any> whenAnyNotNull(vararg options: T?, block: (List<T>)->R) {
if (options.any { it != null }) {
block(options.filterNotNull())
}
}

示例用法:

whenAllNotNull("something", "else", "matters") {
println(it.joinToString(" "))
} // output "something else matters"

这些变化可以更改为返回值,如 let()

使用第一个非空项(Coalesce)

与 SQL Coalesce 函数类似,返回第一个非空项:

fun <T: Any> coalesce(vararg options: T?): T? = options.firstOrNull { it != null }
fun <T: Any> Collection<T?>.coalesce(): T? = this.firstOrNull { it != null }

示例用法:

coalesce(null, "something", null, "matters")?.let {
it.length
} // result is 9, length of "something"


listOf(null, "something", null, "matters").coalesce()?.let {
it.length
}  // result is 9, length of "something"

其他变化

... 还有其他的变化,但是有了更多的规范,这可以缩小范围。

事实上,你可以简单地这样做,你知道吗? ;)

if (first != null && second != null) {
// your logic here...
}

在 Kotlin 使用正常的空检查没有错。

而且对于每个查看您的代码的人来说,它的可读性要高得多。

对于只检查两个值并且不必使用列表的情况:

fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) {
if (value1 != null && value2 != null) {
bothNotNull(value1, value2)
}
}

用法例子:

var firstString: String?
var secondString: String?
ifNotNull(firstString, secondString) { first, second -> Log.d(TAG, "$first, $second") }

对于要检查的任何数量的值,可以使用以下命令:

    fun checkNulls(vararg elements: Any?, block: (Array<*>) -> Unit) {
elements.forEach { if (it == null) return }
block(elements.requireNoNulls())
}

它将被这样使用:

    val dada: String? = null
val dede = "1"


checkNulls(dada, dede) { strings ->


}

发送到块的元素使用通配符,如果你想访问值,你需要检查类型,如果你只需要使用一种类型,你可以将其变换为泛型

实际上,我更喜欢使用以下 helper 函数来解决这个问题:

fun <A, B> T(tuple: Pair<A?, B?>): Pair<A, B>? =
if(tuple.first == null || tuple.second == null) null
else Pair(tuple.first!!, tuple.second!!)


fun <A, B, C> T(tuple: Triple<A?, B?, C?>): Triple<A, B, C>? =
if(tuple.first == null || tuple.second == null || tuple.third == null) null
else Triple(tuple.first!!, tuple.second!!, tuple.third!!)




fun <A, B> T(first: A?, second: B?): Pair<A, B>? =
if(first == null || second == null) null
else Pair(first, second)


fun <A, B, C> T(first: A?, second: B?, third: C?): Triple<A, B, C>? =
if(first == null || second == null || third == null) null
else Triple(first, second, third)

以下是你应该如何使用它们:

val a: A? = someValue
val b: B? = someOtherValue
T(a, b)?.let { (a, b) ->
// Shadowed a and b are of type a: A and b: B
val c: C? = anotherValue
T(a, b, c)
}?.let { (a, b, c) ->
// Shadowed a, b and c are of type a: A, b: B and c: C
.
.
.
}

如果感兴趣的话,这里有两个我用来解决这个问题的函数。

inline fun <T: Any> guardLet(vararg elements: T?, closure: () -> Nothing): List<T> {
return if (elements.all { it != null }) {
elements.filterNotNull()
} else {
closure()
}
}


inline fun <T: Any> ifLet(vararg elements: T?, closure: (List<T>) -> Unit) {
if (elements.all { it != null }) {
closure(elements.filterNotNull())
}
}

用法:


// Will print
val (first, second, third) = guardLet("Hello", 3, Thing("Hello")) { return }
println(first)
println(second)
println(third)


// Will return
val (first, second, third) = guardLet("Hello", null, Thing("Hello")) { return }
println(first)
println(second)
println(third)


// Will print
ifLet("Hello", "A", 9) {
(first, second, third) ->
println(first)
println(second)
println(third)
}


// Won't print
ifLet("Hello", 9, null) {
(first, second, third) ->
println(first)
println(second)
println(third)
}

我通过创建一些函数来解决这个问题,这些函数或多或少地复制了 with 的行为,但是接受多个参数,并且只调用所有参数的函数是非空的。

fun <R, A, B> withNoNulls(p1: A?, p2: B?, function: (p1: A, p2: B) -> R): R? = p1?.let { p2?.let { function.invoke(p1, p2) } }
fun <R, A, B, C> withNoNulls(p1: A?, p2: B?, p3: C?, function: (p1: A, p2: B, p3: C) -> R): R? = p1?.let { p2?.let { p3?.let { function.invoke(p1, p2, p3) } } }
fun <R, A, B, C, D> withNoNulls(p1: A?, p2: B?, p3: C?, p4: D?, function: (p1: A, p2: B, p3: C, p4: D) -> R): R? = p1?.let { p2?.let { p3?.let { p4?.let { function.invoke(p1, p2, p3, p4) } } } }
fun <R, A, B, C, D, E> withNoNulls(p1: A?, p2: B?, p3: C?, p4: D?, p5: E?, function: (p1: A, p2: B, p3: C, p4: D, p5: E) -> R): R? = p1?.let { p2?.let { p3?.let { p4?.let { p5?.let { function.invoke(p1, p2, p3, p4, p5) } } } } }

然后我像这样使用它:

withNoNulls("hello", "world", Throwable("error")) { p1, p2, p3 ->
p3.printStackTrace()
p1.plus(" ").plus(p2)
}?.let {
Log.d("TAG", it)
} ?: throw Exception("One or more parameters was null")

这样做的一个显而易见的问题是,我必须为我需要的每种情况(变量的数量)定义一个函数,但是至少我认为在使用它们时代码看起来是干净的。

你也可以这么做

if (listOfNotNull(var1, var2, var3).size == 3) {
// All variables are non-null
}

我稍微更新了一下预期的答案:

inline fun <T: Any, R: Any> ifLet(vararg elements: T?, closure: (List<T>) -> R): R? {
return if (elements.all { it != null }) {
closure(elements.filterNotNull())
} else null
}

这使得这一切成为可能:

iflet("first", "sconed") {
// do somehing
} ?: run {
// do this if one of the params are null
}

根据@yole 的回答,又有一个想法

fun <T, U, R> Pair<T?, U?>.toLet(body: (List<*>) -> R): R? {
val one = first
val two = second
if (one == null || two == null)
return null
return if (one is Pair<*, *>) {
one.toLet { a ->
body(listOf(a, listOf(two)).flatten())
}
} else {
body(listOf(one, two))
}
}

这样您就可以执行以下操作

(1 to 6 to "a" to 4.5).toLet { (a, b, c, d) ->
// Rest of code
}


也许有点晚了。但是现在存在一个满足这种特定需求的库。它是 康纳德,看看 也许是部门

我将在这里报告一个来自文档的示例用法:

val foo: Int? = 1
val bar: String? = "2"
val baz: Float? = 3.0f


fun useThem(x: Int, y: String, z: Float): Int = x + y.toInt() + z.toInt()


val result: Int? = ::useThem.curry()
.on(foo.maybe)
.on(bar.maybe)
.on(baz.maybe)
.nullable


// or even


val result: Result<Int> = ::useThem.curry()
.on(foo.ifNull("Foo should not be null"))
.on(bar.ifNull("Bar should not be null"))
.on(baz.ifNull("Baz should not be null"))
.result

我喜欢使用一个列表来过滤空值的想法,当我使用相同的类型时,我通常会做一些类似的事情,但是当有多个类型时,为了避免解析为 Any的值,我会这样做:

fun someFunction() {
val value1: String = this.value1 ?: return
val value2: Int = this.value2 ?: return
...
}

它的工作和对我来说是重要的,保持类型的安全。

你可以简化它:

first?.second?.let {}