- Выражение if-else в Kotlin
- Пример использования if
- Пример использования else
- Применение выражения else-if
- Conditions and loops
- When expression
- For loops
- While loops
- Break and continue in loops
- Basic syntax
- Package definition and imports
- Program entry point
- Print to the standard output
- Functions
- Variables
- Creating classes and instances
- Comments
- String templates
- Conditional expressions
Выражение if-else в Kotlin
Наиболее распространенным способом управления порядком выполнения программы является использование выражения if , которое указывает программе на выполнение определенного действия при определенном условии.
Пример использования if
Рассмотрим следующий пример:
Это простое выражение if . Если условие истинно, то выражение выполнит код между фигурными скобками. Если условие ложно, то выражение не будет выполнять данный код. Все просто!
Термин выражение if используется здесь вместо оператора if, поскольку, в отличие от многих других языков программирования, в Kotlin значение возвращается из выражения if . Возвращаемое значение является значением последнего выражения в блоке if .
От вас не требуется использовать возвращаемое значение или присваивать его переменной. Подробнее о возврате значения будет рассказано ниже.
Пример использования else
Вы можете расширить выражение if , чтобы указать действия для случая, когда условие ложное. Это называется условием else. К примеру:
Здесь, если константа animal была бы равна «Кошка» или «Собака» , тогда выражение выполняет первый блок кода. Если константа animal не равна ни «Кошка» , ни «Собака» , тогда выражение выполняет блок внутри else от if выражения, выводя на консоль следующее:
Также можно использовать выражение if-else в одну строку. Рассмотрим, как это поможет сделать код более кратким и читабельным .
Если нужно определить минимальное и максимальное значение из двух переменных, можно использовать выражение if следующим образом:
На данный момент вам должно быть понятно, как это работает, но здесь используется довольно много кода. Взглянем, как можно улучшить код через использование выражения if-else , которое возвращает значение.
Просто уберем скобки и поместим все в одну строку следующим образом:
Так намного проще! Это пример идиоматического кода, который означает, что код пишется ожидаемым образом для определенного языка программирования. Идиомы не только улучшают код, но и позволяют другим разработчикам, знакомым с языком, быстро понять чужую программу.
На заметку: Так как поиск большего или меньшего из двух чисел является очень распространенной операцией, стандартная библиотека Kotlin предоставляет для этой цели две функции: max() и min() . Наверняка в прошлых уроках вы уже встречали их.
Применение выражения else-if
Выражения if можно использовать более эффективно. Иногда нужно проверить одно условие, затем другое. Здесь вступает в игру else-if , встраивая другое выражение if в условие else предыдущего условия if .
Вы можете использовать else-if следующим образом:
Данные вложения if проверяют несколько условий одно за другим, пока не будет найдено истинное условие. Выполняется только тело-if, связанный с первым истинным условием, независимо от того, истинны ли последующие условия else-if . Другими словами, важен порядок ваших условий.
В конце можно добавить вложение else для обработки случая, когда ни одно из условий не выполняется. Если условие else не нужно, его можно не использовать. В этом примере оно требуется, чтобы гарантировать, что константа timeOfDay обладает допустимым значением ко времени его вывода.
В данном примере выражение if принимает число, являющееся временем, и преобразует его в строку, представляющую часть дня, которой принадлежит время. При работе в 24-часовом формате условия проверяются в следующем порядке, по одному пункту за раз:
- Сначала проверяется, если время меньше 6. Если так, значит, это раннее утро;
- Если время не меньше 6, тогда выражение продолжается до первого условия else-if , где проверяется, является ли время меньше 12;
- Когда условие оказывается ложным, выражение проверяет, является ли время меньше 17, затем меньше ли 20, затем меньше ли 24;
- В конечном итоге, если время за пределами диапазона, выражение возвращает недействительное значение.
В коде выше константа hourOfDay равна 12 . Следовательно, код выведет следующее:
Conditions and loops
In Kotlin, if is an expression: it returns a value. Therefore, there is no ternary operator ( condition ? then : else ) because ordinary if works fine in this role.
fun main() < val a = 2 val b = 3 //sampleStart var max = a if (a < b) max = b // With else if (a >b) < max = a >else < max = b >// As expression max = if (a > b) a else b // You can also use `else if` in expressions: val maxLimit = 1 val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b //sampleEnd println(«max is $max») println(«maxOrLimit is $maxOrLimit») >
Branches of an if expression can be blocks. In this case, the last expression is the value of a block:
If you’re using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.
When expression
when defines a conditional expression with multiple branches. It is similar to the switch statement in C-like languages. Its simple form looks like this.
when matches its argument against all branches sequentially until some branch condition is satisfied.
when can be used either as an expression or as a statement. If it is used as an expression, the value of the first matching branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. Just like with if , each branch can be a block, and its value is the value of the last expression in the block.
The else branch is evaluated if none of the other branch conditions are satisfied.
If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions, for example, with enum class entries and sealed class subtypes).
enum class Bit < ZERO, ONE >val numericValue = when (getRandomBit()) < Bit.ZERO ->0 Bit.ONE -> 1 // ‘else’ is not required because all cases are covered >
In when statements, the else branch is mandatory in the following conditions:
- when has a subject of a Boolean , enum , or sealed type, or their nullable counterparts.
- branches of when don’t cover all possible cases for this subject.
enum class Color < RED, GREEN, BLUE >when (getColor()) < Color.RED ->println(«red») Color.GREEN -> println(«green») Color.BLUE -> println(«blue») // ‘else’ is not required because all cases are covered > when (getColor()) < Color.RED ->println(«red») // no branches for GREEN and BLUE else -> println(«not red») // ‘else’ is required >
To define a common behavior for multiple cases, combine their conditions in a single line with a comma:
You can use arbitrary expressions (not only constants) as branch conditions
You can also check a value for being in or !in a range or a collection:
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 option is checking that a value is or !is of a particular type. Note that, due to smart casts, you can access the methods and properties of the type without any extra checks.
when can also be used as a replacement for an if — else if chain. If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true:
You can capture when subject in a variable using following syntax:
fun Request.getBody() = when (val response = executeRequest()) < is Success ->response.body is HttpError -> throw HttpException(response.status) >
The scope of variable introduced in when subject is restricted to the body of this when.
For loops
The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. The syntax of for is the following:
The body of for can be a block.
As mentioned before, for iterates through anything that provides an iterator. This means that it:
- has a member or an extension function iterator() that returns Iterator<> :
- has a member or an extension function next()
- has a member or an extension function hasNext() that returns Boolean .
All of these three functions need to be marked as operator .
To iterate over a range of numbers, use a range expression:
A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.
If you want to iterate through an array or a list with an index, you can do it this way:
Alternatively, you can use the withIndex library function:
While loops
while and do-while loops execute their body continuously while their condition is satisfied. The difference between them is the condition checking time:
- while checks the condition and, if it’s satisfied, executes the body and then returns to the condition check.
- do-while executes the body and then checks the condition. If it’s satisfied, the loop repeats. So, the body of do-while executes at least once regardless of the condition.
Break and continue in loops
Kotlin supports traditional break and continue operators in loops. See Returns and jumps.
Basic syntax
This is a collection of basic syntax elements with examples. At the end of every section, you’ll find a link to a detailed description of the related topic.
You can also learn all the Kotlin essentials with the free Kotlin Core track by JetBrains Academy.
Package definition and imports
Package specification should be at the top of the source file.
It is not required to match directories and packages: source files can be placed arbitrarily in the file system.
Program entry point
An entry point of a Kotlin application is the main function.
Another form of main accepts a variable number of String arguments.
Print to the standard output
print prints its argument to the standard output.
println prints its arguments and adds a line break, so that the next thing you print appears on the next line.
Functions
A function with two Int parameters and Int return type.
A function body can be an expression. Its return type is inferred.
A function that returns no meaningful value.
Unit return type can be omitted.
Variables
Read-only local variables are defined using the keyword val . They can be assigned a value only once.
Variables that can be reassigned use the var keyword.
You can declare variables at the top level.
Creating classes and instances
To define a class, use the class keyword.
Properties of a class can be listed in its declaration or body.
The default constructor with parameters listed in the class declaration is available automatically.
Inheritance between classes is declared by a colon ( : ). Classes are final by default; to make a class inheritable, mark it as open .
Comments
Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.
Block comments in Kotlin can be nested.
See Documenting Kotlin Code for information on the documentation comment syntax.
String templates
Conditional expressions
In Kotlin, if can also be used as an expression.