Nullable as argument


#1

Hello everyone,
I have an issue regarding nullable types in function arguments.

Say I have a function
fun foo(i: Int)
and I want to pass a nullable var to it
var bar: Int? = 1
foo(bar)

If the argument bar is null, I want the function not to be executed,
otherwise bar should be cast to Int and foo should be called with that.

I can’t use the ?. operator since the function is not called on the object,
but with the object as parameter.
I can’t check for null in an if statement, since bar is a var
if(bar != null) foo(bar)
-> Smart cast is impossible…

So how would I do this without losing null safety?
Thanks in advance for your help


#2

bar?.let { bar -> … }


#3

Thanks that worked!
I’m assuming bar?.let(::foo) does the same…