Kotlin Ranges with When expression

Read Time < 1 minute

It’s not been long since I have started using Kotlin but more I use it more I fall in love with it. Most recent thing I have used is Ranges.

Range expressions are formed with rangeTo functions that have the operator form .. which is complemented by in and !in. [kotlinlang]

For example we can use range operator .. with in to see if a value is in the range or not. This can saves us from very complex if-else statements. Look, for example, how, getting an icon for different battery levels can be achieved with Ranges and When.

 

fun BatteryModel.getIconForBattery(): Int = 
when (this.percentage) {
    100 -> R.drawable.icon_battery_100_percent
    in 80..99 -> R.drawable.icon_battery_80_percent
    in 60..79 -> R.drawable.icon_battery_60_percent
    in 40..59 -> R.drawable.icon_battery_40_percent
    in 20..39 -> R.drawable.icon_battery_20_percent
    else -> R.drawable.icon_battery_0_percent
}

Beautiful! isn’t it?

1 thought on “Kotlin Ranges with When expression”

Leave a Comment

Your email address will not be published. Required fields are marked *