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

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.

主站蜘蛛池模板: 修文县| 花莲县| 铁岭县| 阿坝县| 武威市| 交城县| 琼结县| 璧山县| 洛宁县| 长丰县| 乳源| 鹤山市| 安徽省| 和平县| 昌乐县| 康乐县| 南平市| 张家川| 海盐县| 凤冈县| 天气| 阿克苏市| 鄯善县| 利川市| 广汉市| 洛南县| 阿拉尔市| 安达市| 黄山市| 宜阳县| 昌乐县| 阳东县| 东阿县| 郯城县| 海安县| 太原市| 城口县| 闽侯县| 利津县| 文成县| 海宁市|