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

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.

主站蜘蛛池模板: 德钦县| 色达县| 余姚市| 孝感市| 莱阳市| 靖江市| 礼泉县| 福建省| 新竹市| 监利县| 五台县| 贵港市| 历史| 始兴县| 新宾| 天峻县| 宁武县| 苏尼特右旗| 商南县| 故城县| 汉川市| 增城市| 晋宁县| 同仁县| 仲巴县| 雷山县| 梁平县| 通江县| 白水县| 南江县| 绍兴市| 镇巴县| 团风县| 五台县| 韶山市| 朝阳县| 康乐县| 大关县| 巨野县| 亚东县| 乌拉特前旗|