Default parameters

In Kotlin, function parameters can have default values. For the Programmer, the favouriteLanguage and yearsOfExperience data classes have default values (remember that a constructor is a function too):

data class Programmer(val firstName: String,
val lastName: String,
val favouriteLanguage: String = "Kotlin",
val yearsOfExperience: Int = 0)

So, Programmer can be created with just two parameters:

val programmer1 = Programmer("John", "Doe")

But if you want to pass yearsOfExperience, it must be as a named parameter:

val programmer2 = Programmer("John", "Doe", 12) //Error

val programmer2 = Programmer("John", "Doe", yearsOfExperience = 12) //OK

You can still pass all parameters if you want to, but they must be provided in the right order if you aren't using named arguments:

val programmer3 = Programmer("John", "Doe", "TypeScript", 1)
..................Content has been hidden....................

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