Skip to main content

Posts

Showing posts with the label data classes

Destructuring in Kotlin

Introduction This is a process in which we can be able to extract properties of interest from an object  / collection. We have been used to using destructuring in javascript and other functional languages whereas in Java / C# we have not been able to do this. However, kotlin has added the functionality to destructure classes by properties, collections, maps etc. Destructuring classes To enable a class to be destructured, should we do anything in kotlin? The answer is yes and no.. looks puzzling ain't it. Destructuring a class Below is a regular class (non data class) which needs implementation to allow it to be destructured class User ( var mail : String , var deptId : Long ) { operator fun component1 () = mail operator fun component2 () = deptId } Destructuring a data class Below is a declaration of a data class which comes with the support for destructuring for free as like toString, hashcode etc.. data class CompanyUser ( var mail : String , var deptId : Long ) Now that

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