https://kotlinlang.org logo
Title
n

Nicolas Chaduc

05/25/2018, 7:51 AM
Hey, how can I write same in kotlin of that swift code :
if let valueCatchNotNull = valueCanBeNull {
} else {
}
we can catch value not null with
?.let
but can’t use else
o

Olivier Patry

05/25/2018, 7:53 AM
valueCatchNotNull?. let {
  <if not null part>
} ?: <else part>
?
m

marstran

05/25/2018, 7:54 AM
This will execute the else part if the "if not null" part returns null.
👍 1
g

gildor

05/27/2018, 9:58 AM
In many cases smart cast can help without additional ceremony:
if (valueCanBeNull != null) {
   //Cannot be null anymore
} else {
  // Is actually null
}
If smart cast doesn't work for you case (for example you value is mutable nullable of class level or from some third party code, I would prefer just to assign it to local variable and use smart cast like on my previous sample:
val someNullable = someCode.someNullable
if (someNullable != null) {
 // Now smart cast works
}
This common if looks much better for me than really messy let + run