Null check on more than one variable

与世无争的帅哥 提交于 2021-02-11 12:32:38

问题


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

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

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/65904575/null-check-on-more-than-one-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!