Constructor with default parameters

Kotlin allows us to assign default values to constructor parameters. The compiler automatically assigns default values if the object is created without passing the relevant values to the parameters:

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

fun main(args: Array<String>) {

val jon = Person("Jon")
println("name ${jon.name}, age ${jon.age}, height ${jon.height}")

val abid = Person("Abid", 40)
println("name ${abid.name}, age ${abid.age}, height ${abid.height}")

val igor = Person("Igor", 35, 6.0)
println("name ${igor.name}, age ${igor.age}, height ${igor.height}")
}

Take a look at the following output. The default parameter is a really powerful option provided by Kotlin that helps us to write clean and concise code:

If we compare the power of default parameters with the primary and secondary constructors, we notice that a single line of a default parameter can achieve much more than the other approaches, in which we need to write hundreds of lines of code.

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

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