Sat. Nov 27th, 2021
Conditions and loops | Kotlin

If expression

In Kotlin, if is an expression: it returns a price. Therefore, there isn’t a ternary operator (situation ? then : else) as a result of strange if works tremendous on this position.

var max = a
if (a < b) max = b // With else var max: Int if (a > b) {
max = a
} else {
max = b
}

// As expression
val max = if (a > b) a else b

Branches of if branches could be blocks. In this case, the final expression is the worth of a block:

val max = if (a > b) {
print(“Choose a”)
a
} else {
print(“Choose b”)
b
}

If you are utilizing if as an expression, for instance, for returning its worth or assigning it to a variable, the else department is necessary.

When expression

when defines a conditional expression with a number of branches. It is just like the swap assertion in C-like languages. Its easy type appears to be like like this.

when (x) {
1 -> print(“x == 1”)
2 -> print(“x == 2”)
else -> {
print(“x is neither 1 nor 2”)
}
}

when matches its argument towards all branches sequentially till some department situation is glad.

when can be utilized both as an expression or as a press release. If it’s used as an expression, the worth of the primary matching department turns into the worth of the general expression. If it’s used as a press release, the values of particular person branches are ignored. Just like with if, every department generally is a block, and its worth is the worth of the final expression within the block.

The else department is evaluated if not one of the different department circumstances are glad. If when is used as an expression, the else department is necessary, except the compiler can show that every one doable circumstances are coated with department circumstances, for instance, with enum class entries and sealed class subtypes).

enum class Bit {
ZERO, ONE
}

val numericValue = when (getRandomBit()) {
Bit.ZERO -> 0
Bit.ONE -> 1
// the ‘else’ clause shouldn’t be required as a result of all circumstances are coated
}

To outline a typical conduct for a number of circumstances, mix their circumstances in a single line with a comma:

when (x) {
0, 1 -> print(“x == 0 or x == 1”)
else -> print(“otherwise”)
}

You can use arbitrary expressions (not solely constants) as department circumstances

when (x) {
s.toInt() -> print(“s encodes x”)
else -> print(“s does not encode x”)
}

You may test a price for being in or !in a vary or a set:

when (x) {
in 1..10 -> print(“x is in the range”)
in validNumbers -> print(“x is valid”)
!in 10..20 -> print(“x is outside the range”)
else -> print(“none of the above”)
}

Another possibility is checking {that a} worth is or !is of a selected kind. Note that, because of sensible casts, you’ll be able to entry the strategies and properties of the sort with none additional checks.

enjoyable hasPrefix(x: Any) = when(x) {
is String -> x.beginsWith(“prefix”)
else -> false
}

when may also be used as a substitute for an ifelse if chain. If no argument is provided, the department circumstances are merely boolean expressions, and a department is executed when its situation is true:

when {
x.isOdd() -> print(“x is odd”)
y.isEven() -> print(“y is even”)
else -> print(“x+y is odd”)
}

You can seize when topic in a variable utilizing following syntax:

enjoyable Request.getBody() =
when (val response = executeRequest()) {
is Success -> response.physique
is HttpError -> throw HttpException(response.standing)
}

The scope of variable launched in when topic is restricted to the physique of this when.

For loops

The for loop iterates via something that gives an iterator. This is equal to the foreach loop in languages like C#. The syntax of for is the next:

for (merchandise in assortment) print(merchandise)

The physique of for generally is a block.

for (merchandise: Int in ints) {
// …
}

As talked about earlier than, for iterates via something that gives an iterator. This signifies that it:

  • has a member or an extension perform iterator() that returns Iterator<>:

All of those three features have to be marked as operator.

To iterate over a variety of numbers, use a vary expression:

enjoyable essential() {
//sampleStart
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
//sampleEnd
}

A for loop over a variety or an array is compiled to an index-based loop that doesn’t create an iterator object.

If you wish to iterate via an array or a listing with an index, you are able to do it this manner:

enjoyable essential() {
val array = arrayOf(“a”, “b”, “c”)
//sampleStart
for (i in array.indices) {
println(array[i])
}
//sampleEnd
}

Alternatively, you should utilize the withIndex library perform:

enjoyable essential() {
val array = arrayOf(“a”, “b”, “c”)
//sampleStart
for ((index, worth) in array.withIndex()) {
println(“the element at $index is $value”)
}
//sampleEnd
}

While loops

even as and do-while loops execute their physique constantly even as their situation is glad. The distinction between them is the situation checking time:

  • even as checks the situation and, if it is glad, executes the physique and then returns to the situation test.

  • do-while executes the physique and then checks the situation. If it is glad, the loop repeats. So, the physique of do-while executes no less than as soon as whatever the situation.

even as (x > 0) {
x–
}

do {
val y = retrieveData()
} even as (y != null) // y is seen right here!

Break and proceed in loops

Kotlin helps conventional break and proceed operators in loops. See Returns and jumps.

Last modified: 17 September 2021

By admin