有没有办法在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
}
}
答案 0 :(得分:107)
以下是一些变体,具体取决于您要使用的样式,如果您拥有相同或不同类型的所有内容,以及列表未知数量的项目......
对于混合类型,您可以为每个参数计数构建一系列函数,这些函数可能看起来很傻,但对于混合类型可以很好地工作:
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
}
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
}
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
}
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
}
这里有两种风格,第一种是当列表包含所有非空项时执行代码块,第二种是在列表至少有一个非空项时执行相同的代码。两种情况都将非空项目列表传递给代码块:
功能:
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 collectino
}
}
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()
。
与SQL Coalesce函数类似,返回第一个非null项。两种功能:
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"
......还有其他变化,但有更多的规格可以缩小范围。
答案 1 :(得分:9)
您可以为此编写自己的函数:
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
}
答案 2 :(得分:7)
我喜欢使用列表过滤空值的想法,当我使用相同的类型时,我通常会做类似的事情,但是当有多种类型时,为了避免将值解析为Any
,我只是做这样的事情
fun someFunction() {
val value1: String = this.value1 ?: return
val value2: Int = this.value2 ?: return
...
}
它有效,对我来说保持类型安全很重要
答案 3 :(得分:4)
根据Kotlin的各种*NotNull
和*OrNull
函数的精神,您可以创建一个arrayOfNotNullOrNull
函数,以允许您从“多个可空变量”创建一个数组,如果所有变量都不是否则null
和null
:
fun <T : Any> arrayOfNotNullOrNull(vararg elements: T?): Array<T>? {
for (element in elements) {
if (element == null) {
return null
}
}
return elements as Array<T>
}
然后,您可以使用let
:
fun example(first: String?, second: String?) {
arrayOfNotNullOrNull(first, second)?.let {
// Do something just if both are != null
// e.g. val (notNullFirst, notNullSecond) = it ...
}
}
如果您已在集合中拥有可以为空的值,则可以创建类似于kotlin.collections.requireNoNulls
的noNullsOrNull
扩展函数,但返回null
而不是抛出异常。
答案 4 :(得分:3)
对于只检查两个值而不必使用列表的情况:
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") }
答案 5 :(得分:3)
如果有兴趣,这里是我解决此问题的两个功能。
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)
}
答案 6 :(得分:3)
我对预期答案做了一些升级:
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
}
答案 7 :(得分:1)
实际上,你可以简单地做到这一点,你知道吗? ;)
if (first != null && second != null) {
// your logic here...
}
在Kotlin中使用正常的空值检查没有错。
对于每个查看代码的人来说,它的可读性更高。
答案 8 :(得分:1)
我实际上更喜欢使用以下帮助函数来解决它:
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
.
.
.
}
答案 9 :(得分:1)
我通过创建一些函数来解决此问题,这些函数或多或少地复制了with的行为,但是采用了多个参数,并且仅调用所有参数的函数为非null。
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")
一个明显的问题是,我必须为每种情况(变量数)定义一个函数,但是至少我认为使用它们时代码看起来很干净。
答案 10 :(得分:1)
您也可以这样做
if (listOfNotNull(var1, var2, var3).size == 3) {
// All variables are non-null
}
答案 11 :(得分:1)
可能有点晚了。但现在它存在一个满足这一特定需求的库。它是Konad;看看maybe section
我将在此处报告文档中的示例用法:
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
答案 12 :(得分:0)
对于要检查的任何数量的值,您可以使用以下方法:
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 ->
}
发送到块的元素使用通配符,如果要访问值,则需要检查类型,如果只需要使用一种类型,则可以将其更改为泛型
答案 13 :(得分:0)
在撰写本文时,Kotlin 1.3还没有原生机制可以在一个很好的衬里中支持多个链式租借。
Swift语言通过
非常优雅地支持多重链接(我认为)if let a = a, let b = b, let c = a.doSomething(b) {
print(c)
} else {
print("something was null")
}
每当我需要在Kotlin中执行上述操作时,这会让我感到悲伤,因为代码最终变得冗长且有点丑陋。
希望这几天我们能在Kotlin得到类似的东西!
答案 14 :(得分:0)
基于@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
}