Constructor with named parameters

Kotlin allows us to specify the name of an argument when a class instance is created. This approach makes the object-creation more readable and it reduces the chance that we pass the wrong value to the parameters, especially when all of the parameters have the same data type.

To understand this concept, create a Person class and introduce a property, called weight, of the Double type:

class Person(val name: String, var age: Int = 0, var height : Double = 0.0, var weight : Double = 0.0)

fun
main(args: Array<String>) {
val ali = Person(name = "Ali", age = 34, height = 6.1, weight = 78.5)
println("name ${ali.name}, age ${ali.age}, height ${ali.height}, weight ${ali.weight}")
}

Create a Person class object by assigning the initial values. We can assign values to each property by using their name:

If the primary constructor contains a long list of parameters, the values may pass in the wrong order. If we observe the following example closely, the person's weight and height are swapped with each other but the program will still execute without any errors:

    val ali = Person("Ali", 34, 78.5, 6.1)

By using a named parameter, the values can be passed in any order:

class Person(val name: String, var age: Int = 0, var height : Double = 0.0, var weight : Double = 0.0)

fun
main(args: Array<String>) {
val ali = Person(name = "Ali", age = 34, height = 6.1, weight = 78.5)
println("name ${ali.name}, age ${ali.age}, height ${ali.height}, weight ${ali.weight}")

val bob = Person(weight = 73.5, age = 37, name = "Bob", height = 5.8)
println("name ${bob.name}, age ${bob.age}, height ${bob.height}, weight ${bob.weight}")
}

As we can see, both the bob and ali objects are initialized by assigning values in different orders:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.78.83