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

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!

主站蜘蛛池模板: 泊头市| 巢湖市| 大姚县| 贵南县| 佛山市| 册亨县| 河西区| 武穴市| 永德县| 确山县| 兴和县| 闻喜县| 克什克腾旗| 都兰县| 波密县| 三门县| 舞阳县| 巴南区| 定襄县| 社旗县| 南平市| 西乡县| 柞水县| 教育| 渝北区| 宝丰县| 枣庄市| 三河市| 阿坝| 平罗县| 平阳县| 丹东市| 克拉玛依市| 台湾省| 昭通市| 新安县| 富川| 承德县| 连南| 金沙县| 五家渠市|