if-then, a statement in Java; but an expression in Kotlin
Ted Hagos

Ted Hagos @tedhagos

About: Author of Apress books on Java, Android, Spring, and Kotlin. Technical lead at workingdev.net. Full portfolio and credentials at tedhagos.com.

Location:
Manila, Philippines
Joined:
Sep 14, 2018

if-then, a statement in Java; but an expression in Kotlin

Publish Date: Sep 30 '18
13 2

The if construct in Kotlin works almost the same as in Java.

val theQuestion = "Doctor who?"
val answer = "Theta Sigma"
val correctAnswer = ""

if (answer == correctAnswer) {
 println("You are correct")
}
Enter fullscreen mode Exit fullscreen mode

Another example, this time, let's use the else if and else clause.

val d = Date()
val c = Calendar.getInstance()
val day = c.get(Calendar.DAY_OF_WEEK)

if (day == 1) {
 println("Today is Sunday")
}
else if (day == 2) {
 println("Today is Monday")
}
else if ( day == 3) {
 println("Today is Tuesday")
}
else {
  println("Unknown")
}
Enter fullscreen mode Exit fullscreen mode

So far, it looks a lot like how you would you do it in Java. Doesn't it? What's different in Kotlin is, the if construct isn't a statement, it's an expression. Which means, you can assign the result of the if expression to a variable. Like this

val theQuestion = "Doctor who"
val answer = "Theta Sigma"
val correctAnswer = ""

var message = if (answer == correctAnswer) {
 "You are correct"
}
else{
 "Try again"
}
Enter fullscreen mode Exit fullscreen mode

If you have only one statement (each) on the if and else block, you can even shorten the code, like this

var message = if (answer == correctAnswer) "You are correct" else "Try again"
Enter fullscreen mode Exit fullscreen mode

Comments 2 total

  • sergi
    sergiOct 1, 2018

    You can actually do this in Java.

    String message = (answer == correctAnswer) ? "You are correct" : "Try again";
    
    • Ted Hagos
      Ted HagosOct 1, 2018

      Yes you can, but that's the ternary operator (Kotlin has that as well, they call it the "Elvis" operator). The article was just pointing out the slight differences between Kotlin and Java; one of them being some statements in Java are treated as expressions in Kotlin.

Add comment