0

let say I have this variable

   val number : Int? = 12

I want to make control flow based on the variable, if the variable is null then do something, otherwise do something else

in Swift I can make something like this:

if let number = number {
    print(number)
} else {
    // do something else
}

I actually can do like this

if number != null {
   print(number!!) // I want to avoid exclamation mark like this
} else {
   // do something else
}

but I want to avoid exclamation mark, like in print(number!!)

I previously though that I can do something like this

number?.let {

print(it)

} else {
  // else block is not available in let in Kotlin
}

so how to solve this ?

Alexa289
  • 8,089
  • 10
  • 74
  • 178

1 Answers1

0

The ?. means it will be executed only if the left side is not null. The ?: operator executes the right side only if the left side is not null. You may have something like:

theExpression().toCompute().theNumber?.let { number ->
  print("This is my number $number
} ?: run {
  print("There is no number")
}

Here we use T.let extension function for the then clause and run{ } (extension) function for the else clause.

Warning: The semantics is that you expected to return non-null value from the let {...} closure to avoid the `run {..} closure from being executed. Thus the code like: number?.let { null } ?: run { 42 } === 42 (and not null)

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
Eugene Petrenko
  • 4,874
  • 27
  • 36