https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

nadi

03/03/2024, 4:21 PM
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

ephemient

03/03/2024, 4:24 PM
just do it normally
Copy code
val val1 = func1()
val val2 = func2()
check(val1 == null || val2 == null)
return val1 ?: val2
1
🙌 1
n

nadi

03/03/2024, 4:24 PM
but understood that we always want to refrain from using null comparisions
j

Joffrey

03/03/2024, 5:27 PM
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

Klitos Kyriacou

03/04/2024, 10:13 AM
We should refrain from using the non-null assertion operator (
!!
) but checking for null is ok.
💯 1
j

Joffrey

03/04/2024, 10:14 AM
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

ephemient

03/04/2024, 4:02 PM
checkNotNull()
,
requireNotNull()
1
j

Joffrey

03/04/2024, 5:00 PM
Yeah or those ones, too (the overload with message). Just not a plain
!!
without explanation
k

Klitos Kyriacou

03/04/2024, 5:25 PM
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

ephemient

03/04/2024, 5:29 PM
Copy code
val existingKey by map // map["existingKey"]
although it's kind of problematic for keys with names like
existing-key
j

Joffrey

03/04/2024, 5:32 PM
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)