← Kotlin tutorial

Kotlin

Conditionals

if/else if/else work as usual, but in Kotlin if can also be used as an expression that directly produces a value.

Example: if as an expression

fun main() {
    val hour = 14
    val greeting = if (hour < 12) "Good morning" else if (hour < 18) "Good afternoon" else "Good evening"
    println(greeting)
}
Good afternoon

This single line replaces what a separate ternary operator does in languages like Java or JavaScript, Kotlin doesn't have a ? : ternary at all, since if/else used as an expression already covers the same need, arguably more readably once you're used to it.

Example
fun main() {
    val hour = 14
    val greeting = if (hour < 12) "Good morning" else if (hour < 18) "Good afternoon" else "Good evening"
    println(greeting)
}
Output
Good afternoon
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account