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

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.

主站蜘蛛池模板: 昭苏县| 永胜县| 大余县| 平阴县| 霍邱县| 锡林浩特市| 广南县| 平山县| 德惠市| 呼玛县| 花莲市| 新干县| 扶风县| 象州县| 顺平县| 吉首市| 本溪| 文水县| 双流县| 陇川县| 建湖县| 鹿泉市| 牟定县| 新疆| 城口县| 嘉义县| 盖州市| 拜泉县| 通山县| 九龙城区| 鹰潭市| 阜阳市| 闽侯县| 浙江省| 方城县| 宜章县| 宝山区| 招远市| 新野县| 宁津县| 鸡东县|