Kotlin Programming Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

Create a file and name it ifWithKotlin.kt. You can name it anything; it need not be the same as the class name because it is in Java. Now, to get started, you should always declare the main method because the Java virtual machine starts execution by invoking the main method of the specified class.

The main method is as follows:

fun main(args: Array<String>) { }
  1. Let's try a basic if statement in a traditional way to understand how it works:
fun main(args: Array<String>) {
var x:Int
if(10>20){
x = 5
}
else{
x = 10
}
println("$x")
}

In this code block, we assign a value to x in the if and else block and then print it.

  1. Now, let's try the same thing the Kotlin way:
fun main(args: Array<String>) {
var x:Int = if(10>20) 5 else 10
println("$x")
}

In this code block, we assigned a value returned by the if-else block to x. Note how we've used an if statement as a part of the expression on the right-hand side of the expression.

  1. Let's see what else can we do. In the following example, we will try to return something from the expression using the if statement:
fun main(args: Array<String>) {
var x:Int
x = if(10>20) {
doSomething()
25
}
else if (12<13) {
26
}
else{
27
}
println("$x")
}
fun doSomething() {
var a = 6
println("$a")
}

Note how we used the whole block of ifelse. In this case, the if block returns the last statement of the block.

  1. Finally, let's try a more complicated example using a nested ifelse. This will help us understand how values are returned in a nested ifelse structure:
fun main(args: Array<String>) {
var x:Int
x = if(10<20) {
if(4 == 3){
56
}
else{
96
}
}
else if (12>13) {
26
}
else{
27
}
println("$x")
}

//Output: 96

So, if we nest an ifelse block and if the last statement of that ifelse block is another ifelse statement, the value returned by the nested ifelse is returned by the enclosing one. As you can see, 96 is returned by the else block inside the if(10<20) block.

  1. What happens if the ifelse block is not the last statement, like in this example:
 fun main(args: Array<String>) {
var x:Int
x = if(10<20) {

if(4 == 3){
56
}
else{
96
}
565
}
else if (12>13) {
26
}
else{
27
}
println("$x")
}

Clearly, the value returned by the nested ifelse is not being used, and the Kotlin compiler also warns us of this. The reason behind this is because the ifelse block is not the last statement of the parent ifelse block, which is why the returned value is not being used.

Try playing around with the values and logic to see what else you can do with if-else.

The key thing to always remember is that the last statement of the if-else block is returned, which is why it can be used to assign values to any variable.