- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 236字
- 2021-06-25 20:49:30
Creating an email – first attempt
So, at 10 A.M., I plan to drink a coffee in my local cafe. But I also want to contact my manager, since my payslip didn't arrive yesterday. I attempt to create my first email like so:
val mail = Mail("manager@company.com", // TO
null, // CC
null, // BCC
"Ping", // Title
null // Message)
This may have worked in Java, but in Kotlin this wouldn't compile, since we cannot pass null to List<String>. Null-safety is very important in Kotlin:
val mail = Mail("manager@company.com", // TO
listOf(), // CC
listOf(), // BCC
"Ping", // Title
null // Message)
Note that since our constructor receives a lot of arguments, I had to put in some comments, so I wouldn't get lost.
The Kotlin compiler is smart enough to infer the type of list that we pass. Since our constructor receives List<String>, it's enough to pass listOf() for an empty list. We don't need to specify the type like so: listOf<String>(). In Java, Diamond Operator serves the same purpose.
Oh, but I forgot about attachments. Let's change our constructor:
data class Mail(val to: String,
val cc: List<String>,
val bcc: List<String>,
val title: String?,
val message: String?,
val attachments: List<java.io.File>)
But then our instantiation stops compiling again:
val mail = Mail("manager@company.com", // TO
listOf(), listOf(),
"Ping",
null) // Compilation error, No value passed for for parameter 'attachments'
This clearly becomes a mess.
- .NET之美:.NET關鍵技術深入解析
- Programming ArcGIS 10.1 with Python Cookbook
- Learning ASP.NET Core 2.0
- 算法大爆炸:面試通關步步為營
- 實戰低代碼
- 深度學習:算法入門與Keras編程實踐
- 零基礎輕松學SQL Server 2016
- Android應用案例開發大全(第二版)
- Python Data Science Cookbook
- Qlik Sense? Cookbook
- Programming Microsoft Dynamics? NAV 2015
- 區塊鏈項目開發指南
- Oracle 12c從入門到精通(視頻教學超值版)
- JavaScript Concurrency
- 程序員面試金典(第6版)