Like some other modern languages, Kotlin provides us with the ability to set default values for function parameters:
data class Mail(val to: String, val title: String = "", val message: String = "", val cc: List<String> = listOf(), val bcc: List<String> = listOf(), val attachments: List<java.io.File> = listOf())
So, if you would like to send an email without CC, you can do it like that now:
val mail = Mail("one@recepient.org", "Hi", "How are you")
But what about the case where you want to send an email with BCC? Also, not having to specify order with fluent setters was very handy. Kotlin has named arguments for that:
val mail = Mail(title= "Hello", message="There", to="my@dear.cat")
Combining default parameters with named arguments makes creating complex objects in Kotlin a lot easier than before. There's another way to achieve somewhat similar behavior: the apply() function. This is one of the extension functions that every object in Kotlin has. In order to use this approach, though, we'll need to make all the optional fields variables instead of values:
Then we can create our email like this:
val mail = Mail("hello@mail.com").apply { message = "Something" title = "Apply" }
The apply() function is the only one out of the family of scoping functions. We'll discuss how scoping functions work and are their uses in later chapters. Now, while my boss thinks I'm working hard sending all these emails, I can go back to my coffee. It's getting cold now!