another question :slightly_smiling_face: what woul...
# getting-started
n
another question 🙂 what would be the kotlin-idiomatic way to do the following: func1 and func2 return val1 and val2, if val1 and val2 both not null, throw an exception, otherwise return the value that isn't null, or null if both null. im still getting used to the usage of 'let' funtion
i could do: if (val1 != null && val2 != null) tgriw exceptiobn return val1 ?: val2
👌 1
e
just do it normally
Copy code
val val1 = func1()
val val2 = func2()
check(val1 == null || val2 == null)
return val1 ?: val2
✅ 1
🙌 1
n
but understood that we always want to refrain from using null comparisions
j
Why so? Checking for null is great. The problem with nulls in java is that the type system is not aware of them. In Kotlin it is, so you're fine ;)
👆 1
k
We should refrain from using the non-null assertion operator (
!!
) but checking for null is ok.
💯 1
j
Agreed, I found that it's almost always better to use
?: error("describe the broken invariant here")
over just
!!
. Because it also auto-documents why it's not expected to be null, and it does so very clearly if it ever fails
âž• 1
e
checkNotNull()
,
requireNotNull()
âž• 1
j
Yeah or those ones, too (the overload with message). Just not a plain
!!
without explanation
k
But I prefer to avoid having to use any form of null-checking in the first place; for example, instead of
map["existing-key"]!!
you can do
map.getValue("existing-key")
. It's a shame that
getValue
is so much more to type than
[]
.
e
Copy code
val existingKey by map // map["existingKey"]
although it's kind of problematic for keys with names like
existing-key
j
getValue
is slightly better than
!!
regarding the error message, because it describes more clearly what happened (in case of error). However, it still doesn't explain why you thought this would never be null, no tooling can help here. But yeah, sometimes it's good enough (like when the previous line of code is literally checking your invariant)