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("[email protected]").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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.119.81