This is the part 6 of series Java to Kotlin - Learning Simplified. I hope you are learning something new from every part. This part is very simple and easy to grasp. Consider it a break in this series.
If you have not read part 5 (Constructors and Inheritance), please do here.
Index of this Part: If Expression, When Expression, Range, Range with Step, For In Loop, Labelled Block
If as an Expression
As we know almost every language has if-else
conditional control flow. Java and Kotlin both are no exception. They both have if-else
. Interestingly in Kotlin if-else
can be used as expression as well. Here is snippet:
// Kotlin
val abc = if(condition) value_1 else value_2
fun doSomething(){
return if(condition) value_1 else value_2
}
💡 Both of the ways shown above are not possible in Java.
When Expression
I am sure you are aware of switch
statement in Java. Switch can be used when you have if-else
ladder. Kotlin does not have switch
keyword, It has when
keyword offering same feature + more power at your disposal. Here is a snippet of code:
// Kotlin
val x = (Math.random() * 100).toInt()
if(x == 10) {
} else if (x == 20) {
} else if(x == 30) {
} else if(x == 40) {
} else {
}
💡 As you saw above if-else
ladder is not fun to read. Java has a switch-case
offering, Here is Java solution:
// Java
switch(x){
case 10:
break;
case 20:
break;
case 30:
break;
case 40:
break;
case 50:
break;
default:
break;
}
💡 This is surely better than if-else ladder but Java comes with its own overheads. There is a break after every case. If you do not add the break, next case will execute irrespective of the match. Honestly, its not nice. But kotlin played smart
here and introduced when
, Here is a snippet:
// Kotlin
when(x) {
10 -> doSomething()
20 -> {
doSomething2()
}
30 -> doThat()
else -> {}
}
💡 As you saw above when is equivalent to switch but we do not need break statement after a block. Only the matching block will execute otherwise else block will.
Power of When
In Java switch, we can combine two cases, lets say you want to execute two blocks. X is either 10 OR 20. In java you can write case 10 and case 20 without a break in between But in Kotlin all you need is a comma
// Kotlin
when(x) {
10, 20 -> {}
30, 40 -> {}
}
What to do if you want to match more than 2 conditions
One answer is use multiple values with comma
// Kotlin
when(x) {
10, 20, 30, 40 -> {}
50, 60 -> {}
}
Other solution is to use Range
🔥 Range ..
Kotlin offers a syntax ..
whenever we need a range, could be range of numbers, chars etc. 1..10
means from 1 to 10 both inclusive. A..Z
means all the capital alphabets. We can use range at multiple places, When block and for loop are two common use cases.
When with range
// Kotlin
when(x) {
in 1..10 -> {}
in 2..20 -> {}
in 3..30 -> {}
in 4..40 -> {}
in 5..50 -> {}
in 6..60 -> {}
}
In the above code, if x is between 1 to 10 (both inclusive), the first block will execute.
We can use !in
with range as well. It means not in range.
When with range
// Kotlin
when(x) {
!in 1..10 -> {}
in 2..20 -> {}
}
!in 1..10
means not in 1 to 10, Any number not 1 to 10.
When with is
Do you remember is
? it is used to check instance of in Kotlin. You can use it with when
// Kotlin
when(x){
is String-> {}
is Number-> {}
is XYZ-> {}
}
🔥 You can use variable declaration in when block. It is not allowed in Java
// Java
switch(final int x){} ❌ not allowed
// Kotlin
when(val x = "Gaurav") { ✅ allowed
"Gaurav" -> println(x.toLowerCase())
}
I hope you are amazed with the power of when
, if not it has more to offer. There are cases when we have conditions like <
>
or null check
or something else. When can be used without a variable as well.
// Java
switch { ❌ not allowed
}
// Kotlin 🔥🔥
when { ✅ allowed
x > y -> {}
4 < 5 -> {}
obj == null -> {}
else ->{}
}
One more, I promise. when
can be used as expression as well. This is amazing.
// Kotlin
fun doSomething():String{
return when {
x > y -> {}
4 < 5 -> {}
obj == null -> {}
else ->
}
}
💡 else is mandatory in such cases and the last statement of the block is returned
🔥 Range ..
with step
In last example of range we saw we can use 1..10
to express a range of 1 to 10. But what if we need all the even numbers from 1 to 100? That too is a range. There is a syntax for this as well. It is called step
0..100 step 2
is the range of all the even numbers till 100
There is nothing like that in Java
For Loop (foreach)
In java we have a foreach loop, there is a better alternative in Kotlin. Lets say we have an array of String name cities
. Here is a snippet:
// Java
for(String city:cities) {}
// Kotlin
for(city:String in cities){}
The syntax is for in
, we just saw above in
syntax works very well with range as well. How about we combine for loop with range
// Kotlin
for(i in 1..10){}
The java equivalent is for i
loop
// Java
for (int i=1; i<=10; i++){}
In my opinion, Kotlin variant is more readable. Wait, do you remember step
with range
? How about we add step in for loop?
// Kotlin, loop with i = 1, 3, 5, 7.. (equivalent of += in java)
for(i in 1..10 step 2){}
All of the step
we saw are in increment fashion. What about decrement? In Java, we can easily do i=10; i>=0;i--
, how about in Kotlin?
// Kotlin
for(i in 10 downTo 1 step 2){}
The above snippet will work with i = 10, 8, 6 ...
Remember 10..1
will not work!!
💡 for-in
can be used with any type which has iterator
, It means it can be used with arrays, collections.
Labelled Block
This is one of the feature a very few developers use. Java and Kotlin both offer labelled blocks. The syntax is little different. Assume you are in nested loop and you want to break
from the outer loop, Here is the snippet:
// Java
iloop:
for (int i = 0; i < 10; i++) {
jloop:
for (int j = 0; j < 10; j++) {
kloop:
for (int k = 0; k < 10; k++) {
if (k == 3) {
break jloop;
}
if (k == 4) {
break iloop;
}
}
}
}
// Kotlin
iloop@
for (i in 1..10) {
jloop@
for (j in 1..10) {
kloop@
for (k in 1..10) {
if (k == 3) {
break@jloop
}
if (k == 4) {
break@iloop
}
}
}
}
💡 Kotlin has the syntax name@
for labelled blocks and while using you have to use @name
Summary
We saw power of kotlin in tiny offerings like If as an expression
, and When
block which is powerful alternative to switch. When can be used when you have a direct comparison like switch OR when you have multiple if elses
. It can also be used as an Expression
.
Then we saw range
the syntax ..
can be used in places like comparison inside when OR for loop. Decrement range can be calculated with downTo
syntax. Range with step
can be used when the increment OR decrement step is other than 1.
For in loop is similar to Java for each loop and can be combined with range. It can be used with any type which has iterator like array and collection.
Finally we saw Labelled block is same like Java with different sytanx label@
.