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?
From the `when` statement to the range expressions, everything about this syntax is great. I’ve just started using Kotlin myself, and I really love it.