- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 254字
- 2021-06-25 20:49:30
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!
- 觸·心:DT時代的大數據精準營銷
- C語言程序設計案例教程(第2版)
- Android項目開發入門教程
- Python數據分析入門與實戰
- Raspberry Pi Networking Cookbook(Second Edition)
- Visual Basic編程:從基礎到實踐(第2版)
- Android Development with Kotlin
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- Visual C#.NET程序設計
- Learning ArcGIS for Desktop
- BeagleBone Black Cookbook
- 軟件體系結構
- Visual FoxPro 6.0程序設計
- Maker基地嘉年華:玩轉樂動魔盒學Scratch
- Laravel Design Patterns and Best Practices