空检查多个变量 [英] Null check on more than one variable

查看:54
本文介绍了空检查多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Kotlin中重新格式化这段代码,使其变得更小? 如果两者都不等于null,则函数应将A和B作为对返回.否则,它应该返回null.我的第一个想法是这样的:

is it possible to reformat this piece of code in Kotlin, that it gets a bit smaller? The function should return A and B as a Pair, if both are unequal to null. Else it should return null. My first idea was like this:

private fun <A, B> zip(a: A?, b: B?): Pair<A, B>? =
    if (a != null && b != null)
        a to b
    else
        null

然后,我决定使用Elvis Operator.所以现在看起来像这样:

Then I decided to use the Elvis Operator. So it now looks like this:

private fun <A, B> zip(a: A?, b: B?): Pair<A, B>? {
    a ?: return null
    b ?: return null
    return a to b
}

但是我正在寻找的只是这样的东西:

But what I am looking for is just something like this:

private fun <A, B> zip(a: A?, b: B?): Pair<A, B>? = 
    // This code obviously doesn't compile but is their any way to do it similar to this?
    a, b ?: return null
    return a to b

提前谢谢!

推荐答案

一个相当简洁的选择是创建对,然后对其进行过滤:

One fairly concise option is to create the Pair and then filter it:

(a to b).takeIf{ a != null && b != null }

但这不是很好:它有时会不必要地创建一个对,结果类型将使对参数都可以为空,即使您知道它们也不能为空.

But this isn't very good: it'll sometimes create a Pair unnecessarily, and the result type will have the Pair params both nullable, even though you know they can't be.

您可以编写扩展功能使其更简单.

You could write an extension function to make it simpler.

否则,我认为您不能做得更好:

Otherwise, I don't think you can do better than:

if (a != null && b != null) a to b else null

播放时间稍长一些,但效率更高且键入更严格.

which is slightly longer-winded but has better efficiency and stricter typing.

这篇关于空检查多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆