- 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.
- Visual Basic程序設計(第3版):學習指導與練習
- Wireshark Network Security
- Magento 2 Development Cookbook
- 算法訓練營:提高篇(全彩版)
- 微信小程序全棧開發技術與實戰(微課版)
- 時空數據建模及其應用
- Couchbase Essentials
- Struts 2.x權威指南
- PyQt編程快速上手
- 監控的藝術:云原生時代的監控框架
- Learning Kotlin by building Android Applications
- Java程序設計實用教程(第2版)
- Blender 3D Cookbook
- Swift 2 Design Patterns
- Cinder:Begin Creative Coding