Control flow
You could say that the control flow is the bread and butter of writing programs. We'll start with two conditional expressions, if and when.
The if expression
In Java, if is a statement. Statements do not return any value. Let's look at the following function, which returns one of two possible values:
public String getUnixSocketPolling(boolean isBsd) {
if (isBsd) {
return "kqueue";
}
else {
return "epoll";
}
}
While this example is easy to follow, in general, having multiple return statements is considered bad practice because they often make the code harder to comprehend.
We could rewrite this method using Java's var keyword:
public String getUnixSocketPolling(boolean isBsd) {
var pollingType = "epoll";
if (isBsd) {
pollingType = "kqueue";
}
return pollingType;
}
Now, we have a single return statement, but we had to introduce a mutable variable. Again, with such a simple example, this is not an issue. But, in general, you should try to avoid mutable shared state as much as possible, since such code is not thread-safe.
Why are we having problems writing that in the first place, though?
Contrary to Java, in Kotlin, if is an expression, meaning it returns a value. We could rewrite the previous function in Kotlin as follows:
fun getUnixSocketPolling(isBsd: Boolean): String {
return if (isBsd) {
"kqueue"
} else {
"epoll"
}
}
Or we could use a shorter form:
fun getUnixSocketPolling(isBsd: Boolean): String = if (isBsd) "kqueue" else "epoll"
Due to the fact that if is an expression, we didn't need to introduce any local variables.
Here, we're again making use of single-expression functions and type inference. The important part is that if returns a value of the String type. There's no need for multiple return statements or mutable variables whatsoever.
Important Note:
Single-line functions in Kotlin are very cool and pragmatic, but you should make sure that somebody else other than you understands what they do. Use with care.
The when expression
What if (no pun intended) we want to have more conditions in our if statement?
In Java, we use the switch statement. In Kotlin, there's a when expression, which is a lot more powerful, since it can embed some other Kotlin features. Let's create a method that's given a superhero and tells us who their archenemy is:
fun archenemy(heroName: String) = when (heroName) {
"Batman" -> "Joker"
"Superman" -> "Lex Luthor"
"Spider-Man" -> "Green Goblin"
else -> "Sorry, no idea"
}
The when expression is very powerful. In the next chapters, we will elaborate on how we can combine it with ranges, enums, and sealed classes as well.
As a general rule, use when if you have more than two conditions. Use if for simple cases.