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

Creating an email – second attempt

Let's try a fluent setter approach instead. We'll have only mandatory fields in our constructor, and all others will become setters, so the creation of a new email would look something like this:

Mail("manager@company.com").title("Ping").cc(listOf<String>())

That's a lot nicer for many reasons:

  • The order of fields can now be arbitrary, unlike with the constructor.
  • It's clearer which field is being set, no need for comments anymore.
  • Optional fields don't need to be set at all. As an example, the CC field is set, while the BCC field is omitted.

Let's see one way of implementing this approach. There are other convenient ways to do it, which we'll discuss in Chapter 10, Idioms and Anti-Patterns:

data class Mail(// Stays the same
private var _message: String = "",
// ...) {
fun message(message: String) : Mail {
_message = message
return this
}
    // Pattern repeats for every other variable
}

Using underscores for private variables is a common convention in Kotlin. It allows us to avoid repeating this.message = message and mistakes such as message = message.

This is nice, and very similar to what we may achieve in Java. Although we did have to make our message mutable now. But Kotlin provides two other ways that you may find even more useful.

主站蜘蛛池模板: 岗巴县| 台江县| 通海县| 玛多县| 包头市| 石景山区| 龙口市| 资阳市| 岳普湖县| 宜兰县| 盐亭县| 南江县| 九龙坡区| 武宁县| 崇文区| 临颍县| 安阳市| 米脂县| 潮州市| 兴文县| 汾阳市| 莱州市| 建阳市| 阳新县| 隆德县| 花莲市| 阳泉市| 北安市| 梅河口市| 威海市| 刚察县| 宁乡县| 安远县| 南康市| 尼玛县| 合阳县| 巴东县| 临朐县| 曲麻莱县| 北碚区| 平乐县|