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

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.

主站蜘蛛池模板: 循化| 高尔夫| 濉溪县| 盈江县| 成武县| 吐鲁番市| 南宫市| 彭泽县| 黑龙江省| 玛纳斯县| 江津市| 丰原市| 平潭县| 长武县| 凤阳县| 利川市| 汤阴县| 崇州市| 兰坪| 鄯善县| 三门县| 静安区| 大宁县| 邵阳市| 张家界市| 晋宁县| 呼伦贝尔市| 临海市| 高平市| 崇义县| 镇宁| 姚安县| 金阳县| 富阳市| 贵州省| 伽师县| 西华县| 临夏市| 江达县| 新和县| 嘉善县|