If I have a function that requires not null variab...
# getting-started
k
If I have a function that requires not null variables, what is the best way to null check them before calling the function?
d
Copy code
if (foo != null) {
  myFunction(foo)
}
☝️ 1
The compiler will automatically smart-cast to the non-null type inside the if-expression. https://kotlinlang.org/docs/reference/typecasts.html#smart-casts
👍 3
e
If the function returns a result that you're using for assignment, you can also inline
if/else
with a default value or use non-null assertions, if you want an exception to be thrown if any of the variables are null.
a
foo?.let{ myFunction(it) }
c
If it is considered an error if null you could do:
Copy code
require(foo!=null) { "foo is required" }
myFunction(foo)
m
@corneil can also make it nicer with
Copy code
requireNotNull(foo) { "..." }
c
Ofcourse, I keep forgetting that one
d
Copy code
if(foo == null) return
myFunction(foo)