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 arguments
printColors(*colors, message = "Color Name is: ") //array is destructured
}
fun printColors(vararg colors: Color, message: String) {
for (c in colors) println("${message} ${c.colorName}")
}
data class Color(val colorName: String)
Code walkthrough
In the above code, we are creating c1,c2,c3 as Colors which are combined into an array using the arrayOf as given below
val colors = arrayOf(c1, c2, c3)
We get colors as Color[]. Now if we need to add any item to the array, we would have to create a new array and then loop through the existing items and add to the array.
val manyColors = arrayOf(*colors, c2.copy())
In the above line, we are destructing the array into individual elements and then creating a new array by adding one more color as c2.copy()
fun printColors(vararg colors: Color, message: String) {
for (c in colors) println("${message} ${c.colorName}")
}
In the above code snippet, we are building a method that can take anything from 1 color to many colors as input through the use of varargs.
In case the consumer of this method is having the data in array format, it can be supplied as such in Java without any issues. In Kotlin, the strict type safety check disallows that and we have to destructure the array to the arguments, this can be done simply by the below line of code
printColors(*colors, message = "Color Name is: ") //array is destructured
The same method can be invoked with separate objects as arguments like the one given below
printColors(c1, c2, c3, message = "The color is: ") // variable number of arguments
This is how Kotlin helps us use a consistent signature for simple argument differences not having to have overloads and redundant code for argument signature changes.
Comments
Post a Comment