Personally, I'd go with 2, which is how I dealt wi...
# announcements
g
Personally, I'd go with 2, which is how I dealt with this in Java
s
3 is just 2 with extra bones, I wouldn’t bother
b
I think option 1 is the best solution. I sometimes use option 2 if I have a function that should execute some optional behaviour. But if a function depends on a non null value it should fail, when called with null
g
With the assignment notation, somewhat. I'm thinking readability here, and having either a whole extra closure wrapping around or such notation seems suboptimal to me
s
Right. If you’re really okay with the method no-oping if passed
null
, then I’d say you ought to make it explicit
could shorten it to
obj ?: return
👍 1
e
Copy code
fun method(obj: Class?) {
    requireNotNull(obj)
    // ...
}
👍 2
g
Problem is that making it explicit is noneffective towards Java
Nice one, @enleur, didn't know about that
s
I thought
requireNotNull()
doesn’t yet work with smart-casting
b
I don’t like @enleur’s variant. Now the function contract says that it accepts
null
but the function actually fails.
👆 4
@Shawn you can use
val x = requireNotNull
s
I see
g
It could work as an interoperability operator when you use an already non-null argument
It would avoid Java nulls to pass through, which is nice, but not work as an assertion, thus why smart-cast isn't applied
So, what I understood is that it should be used like that:
Copy code
fun method(obj: Class) {
    requireNotNull(obj)
    // ...
}
b
You don’t need any null checks if you declare the argument as notNull. The compiler adds them automatically.
g
And what happens if java code calls the method with what happens to be a null object?
Static analysis would probably stress that possibility, since method contract would be similar to
@NonNull
, but afaik it doesn't avoid anything
b
The kotlin compiler adds a call to
Intrinsics.checkParameterIsNotNull
for all parameters. This will throw an
InvalidArgumentException
👍 3
n
Could do it as an expression if don’t want to return anything
Copy code
fun method(obj: Class?) = obj?.let {

}
g
Well, let allows for values returning, just would need to append an
?: defaultValue
to the end