Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

kotlin - Null check on more than one variable

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!

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...