- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 272字
- 2021-06-25 20:49:24
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:
- The return type could be inferred
- The return as the last line can be omitted
- 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.
- UML和模式應用(原書第3版)
- CentOS 7 Server Deployment Cookbook
- Mastering phpMyAdmin 3.4 for Effective MySQL Management
- Xcode 7 Essentials(Second Edition)
- Python從入門到精通(精粹版)
- Java 9 Programming Blueprints
- 區塊鏈:以太坊DApp開發實戰
- HTML5 and CSS3 Transition,Transformation,and Animation
- HTML5入門經典
- 編程與類型系統
- Arduino可穿戴設備開發
- Learning Splunk Web Framework
- UI動效設計從入門到精通
- C/C++代碼調試的藝術(第2版)
- Puppet 5 Beginner's Guide(Third Edition)