- 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.
- Puppet 4 Essentials(Second Edition)
- Implementing Modern DevOps
- INSTANT OpenCV Starter
- AngularJS深度剖析與最佳實踐
- Processing互動編程藝術
- Unity 5.x By Example
- Rust Essentials(Second Edition)
- Instant Lucene.NET
- 網絡數據采集技術:Java網絡爬蟲實戰
- Mockito Essentials
- Go語言入門經典
- Advanced Python Programming
- Laravel Design Patterns and Best Practices
- Wearable:Tech Projects with the Raspberry Pi Zero
- Google Maps JavaScript API Cookbook