https://kotlinlang.org logo
Title
g

gabrielfv

10/19/2018, 3:22 PM
How would you deal with a method that depends on a non-null value but is called by java code that may pass a null value? 1️⃣ (May produce NPE when called from Java)
fun method(obj: Class) { //... }
2️⃣ (Will do nothing when
obj
is null)
fun method(obj: Class?) {
    if (obj == null) return
    // ...
}
3️⃣ (Behaves like 2, assignment notation also applies
method(...) = obj?.let{
, which may be seen as better alternative?)
fun method(obj: Class?) {
    obj?.let {
        // Wraps whole method around this block, up to 10 lines of code
    }
}
2️⃣ 1
m

Mike

10/19/2018, 3:25 PM
Depends. If being called with a null is an error, you can use
checkNotNull
or
requireNotNull
at the top which will throw an IllegalArgumentException/IllegalStateException. Until 1.3 is released, you’ll end up with
val obj = checkNotNull(objMaybeNull)
1.3 leverages contracts and the assignment won’t be required anymore.
👍 1
b

bartvh

10/21/2018, 11:08 AM
Why would that be better than just using method 1, which already throws an exception if called with
null
?
m

Mike

10/21/2018, 2:15 PM
Hmmm, now that I look at it, I agree. There’s negligible value in ‘converting’ the NPE to an IllegalArgument/IllegalState exception. Either receiving a null is an exception, at which point NPE is the best, or it isn’t an exception, in which case the signature of the method would be changed.