https://kotlinlang.org logo
Title
g

gabrielfv

10/19/2018, 3:22 PM
Personally, I'd go with 2, which is how I dealt with this in Java
s

Shawn

10/19/2018, 3:23 PM
3 is just 2 with extra bones, I wouldn’t bother
b

Burkhard

10/19/2018, 3:24 PM
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

gabrielfv

10/19/2018, 3:24 PM
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

Shawn

10/19/2018, 3:25 PM
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

enleur

10/19/2018, 3:26 PM
fun method(obj: Class?) {
    requireNotNull(obj)
    // ...
}
👍 2
g

gabrielfv

10/19/2018, 3:26 PM
Problem is that making it explicit is noneffective towards Java
Nice one, @enleur, didn't know about that
s

Shawn

10/19/2018, 3:27 PM
I thought
requireNotNull()
doesn’t yet work with smart-casting
b

Burkhard

10/19/2018, 3:27 PM
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

Shawn

10/19/2018, 3:28 PM
I see
g

gabrielfv

10/19/2018, 3:28 PM
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:
fun method(obj: Class) {
    requireNotNull(obj)
    // ...
}
b

Burkhard

10/19/2018, 3:31 PM
You don’t need any null checks if you declare the argument as notNull. The compiler adds them automatically.
g

gabrielfv

10/19/2018, 3:32 PM
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

Burkhard

10/19/2018, 3:35 PM
The kotlin compiler adds a call to
Intrinsics.checkParameterIsNotNull
for all parameters. This will throw an
InvalidArgumentException
👍 3
n

neil.armstrong

10/19/2018, 3:35 PM
Could do it as an expression if don’t want to return anything
fun method(obj: Class?) = obj?.let {

}
g

gabrielfv

10/19/2018, 4:02 PM
Well, let allows for values returning, just would need to append an
?: defaultValue
to the end