Skip to main content

Posts

Showing posts with the label array destructuring

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

varargs and array destructuring in Kotlin

Introduction The following post illustrates the use of varargs (variable number of arguments) and array destructing feature in Kotlin langauge. varargs This feature allows multiple arguments of a same type to be passed to a method and not using a collection like Array or list. This feature in java is implemented using the 3 consecutive dots notation given below ... Java Example public String getByValues (String... values) { // ... } Array destructuring With array destructuring, we can be able to use the elements of the array without looping through or pulling out by index which needs careful access as we might get array out of bounds exceptions if not checked. Sample Code fun main() {     val c1 = Color( "red" )     val c2 = Color( "Blue" )     val c3 = Color( "Green" )     val colors = arrayOf(c1, c2, c3)     val manyColors = arrayOf(*colors, c2.copy())     printColors(c1, c2, c3, message = "The color is: " ) // variable number of arg