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

Using the if expression

Previously it was noted that Kotin likes variables to be assigned only once. And it also doesn't like nulls so much. You probably wondered how that would ever work out in the real world. In Java, constructs such as this are quite common:

public String getUnixSocketPolling(boolean isBsd) {
String value = null;
if (isBsd) {
value = "kqueue";
}
else {
value = "epoll";
}

return value;
}

Of course, this is an oversimplified situation, but still, you have a variable that at some point absolutely must be null, right?

In Java, if is just a statement and doesn't return anything. On the contrary, in Kotlin, if is an expression, meaning it returns a value:

fun getUnixSocketPolling(isBsd : Boolean) : String {
val value = if (isBsd) {
"kqueue"
} else {
"epoll"
}
return value
}

If you are familiar with Java, you can easily read this code. This function receives a Boolean (which cannot be null), and returns a string (and never a null). But since it is an expression, it can return a result. And the result is assigned to our variable only once.

We can simplify it even further: 

  1. The return type could be inferred
  2. The return as the last line can be omitted
  3. A simple if expression can be written in one line

So, our final result in Kotlin will look like this:

fun getUnixSocketPolling(isBsd : Boolean) = if (isBsd) "kqueue" else "epoll"

Single line functions in Kotlin are very cool and pragmatic. But you should make sure that somebody else other than you can understand what they do. Use with care.

主站蜘蛛池模板: 澄江县| 紫金县| 香港| 清新县| 吉林省| 博白县| 山西省| 德兴市| 和静县| 原平市| 南澳县| 澎湖县| 明溪县| 会东县| 沙田区| 迁西县| 罗山县| 汉源县| 翼城县| 商水县| 获嘉县| 常州市| 南丹县| 黄龙县| 广昌县| 凉城县| 禹州市| 南通市| 高台县| 三台县| 平江县| 大余县| 亳州市| 沈阳市| 巴塘县| 灵璧县| 特克斯县| 文化| 柯坪县| 永年县| 嘉鱼县|