Skip to main content

Posts

Showing posts with the label switch

when blocks in Kotlin

when This post shows multiple ways in which we can use the when  block in Kotlin We can start with a typical use of when (like in switch statements) enum class Season { SPRING , SUMMER , FALL , WINTER } To execute logic based on the season, we write the below snippet of code when ( timeOfYear ) { Season . SPRING -> println(" Flowers are blooming") Season . SUMMER -> println("It's hot!") Season . FALL -> println("It's getting cooler") Season . WINTER -> println("I need a coat") } In case we wanted to get the value rather than print based on the timeOfYear, we can use the below snippet of code, where we return the value and it can be returned in the overall when block val str = when ( timeOfYear ) { Season . SPRING -> "Flowers are blooming" Season . SUMMER -> "It's hot!" Season . FALL -> "It's getting cooler" Season . WINTER -> { "