How would you deal with a method that depends on a...
# announcements
g
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)
Copy code
fun method(obj: Class) { //... }
2️⃣ (Will do nothing when
obj
is null)
Copy code
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?)
Copy code
fun method(obj: Class?) {
    obj?.let {
        // Wraps whole method around this block, up to 10 lines of code
    }
}
2️⃣ 1
m
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
Why would that be better than just using method 1, which already throws an exception if called with
null
?
m
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.