官术网_书友最值得收藏!

Creating an email – the Kotlin way

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!

主站蜘蛛池模板: 黎平县| 台州市| 花垣县| 德安县| 江华| 广南县| 邵东县| 四平市| 屏边| 株洲市| 公主岭市| 千阳县| 中江县| 乌兰浩特市| 日照市| 西吉县| 屏东市| 海口市| 海原县| 金昌市| 凉山| 大冶市| 扶余县| 平顺县| 宿州市| 金乡县| 上林县| 长沙县| 柏乡县| 靖州| 黄山市| 丰都县| 福清市| 保定市| 苏尼特右旗| 湟中县| 金秀| 宜章县| 芜湖县| 清新县| 榆社县|