Named parameters

Ideally, our functions should not have too many parameters, but this isn't always the case. Some functions tend to be big, for example, the data class constructors (constructors are technically a function that returns a new instance).

What is the problem with functions with many parameters?

  • They are hard to use. This can be alleviated or fixed with default parameters that we will cover in the next section, Default parameters.
  • They are hard to read—named parameters to the rescue.
  • They are probably doing too much. Are you sure that your function isn't too big? Try to refactor it and clean up. Look for possible side effects and other harmful practices. A special case is data class constructors, as they are just autogenerated assignments.

With named parameters, you can add readability to any function invocation.

Let's use a data class constructor as an example:

typealias Kg = Double
typealias cm = Int

data class Customer(val firstName: String,
val middleName: String,
val lastName: String,
val passportNumber: String,
val weight: Kg,
val height: cm)

A normal invocation will look like this:

val customer1 = Customer("John", "Carl", "Doe", "XX234", 82.3, 180)

But including named parameters will increase the information available for the reader/maintainer and reduce mental work. We can also pass the parameters in any order that is more convenient or meaningful for the actual context:

val customer2 = Customer(
lastName = "Doe",
firstName = "John",
middleName = "Carl",
height = 180,
weight = 82.3,
passportNumber = "XX234")

Named parameters are very useful when they are combined with a vararg parameter:

fun paramAfterVararg(courseId: Int, vararg students: String, roomTemperature: Double) {
//Do something here
}

paramAfterVararg(68, "Abel", "Barbara", "Carl", "Diane", roomTemperature = 18.0)
..................Content has been hidden....................

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