Skip to main content

Posts

Showing posts with the label smart cast

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 -> { "

Kotlin Data Classes and Smart Casts

Introduction Kotlin is a language that is built by the Jetbrains team and opensource contributors. The following are the goals that this language helps us achieve (not full set, for more details please visit kotlinlang.org Modern, concise and safe programming language A productive way to write server‑side applications (still using the frameworks that target JVM) Cross-platform layer for native applications Big, friendly and helpful community Kotlin Data Classes Below I am giving some of the kotlin snippets and short descriptions on what they can perform. Keep in mind that kotlin achieves very concise code data class Person ( val name: String , val age: Int ){     } fun getPeople(): List <Person> {     return listOf(Person( "Alice" , 29 ), Person( "Bob" , 31 )) } fun comparePeople(): Boolean {     val p1 = Person( "Alice" , 29 )     val p2 = Person( "Alice" , 29 )     return p1 == p2   // should be true } In the snippet above, we