https://kotlinlang.org logo
Title
m

Michael

02/07/2019, 8:11 PM
I have a lambda and I’m trying to have it return null from within an if statement; but it seems that it just exits the if and moves on to the last line:
{ .....some lines.... if (condition) { null } ..... final value }
d

Dominaezzz

02/07/2019, 8:12 PM
You'll need to do
if (condition) { null } else { ..... final value }
I think.
☝️ 1
k

karelpeeters

02/07/2019, 8:12 PM
Or use
return@foo null
.
m

Michael

02/07/2019, 8:23 PM
👍🏼 Thanks. That got me working.
the different syntax between functions and lambdas always gets me a little bit.
g

groostav

02/07/2019, 9:06 PM
Yeah I dont blame you, would be nice of the compiler could flag
if(condition) { null } otherValue
as failing to compile with a compiler error something along the lines of
if(...) { null }
, using
null
without a parent statement is illegal in this context. Either assign the expression to a value, return it, or simply invoke the condition.
is there no intelliJ inspection for same as suspicious? I know that
if(condition)
is a problem because
condition
may have side effects, but
if(ANY_EXPR) { CONSTANT_EXPR }
is odd even if
ANY_EXPR
has a side effect when
CONSTANT_EXPR
is unused --and of course, in the overwhelming majority of cercomstances, people use
ANY_EXPR
as being ref-transparent, so the whole thing is almost certainly not what the programmer wanted.