Kotlin Lec 3 2020
Kotlin Lec 3 2020
Программирование на Kotlin
(p.3 – control flow)
Similarly, you can find out if two values are not equal using the != operator:
val doesOneNotEqualTwo = (1 != 2) // true
Boolean operators
• The prefix ! operator, also called the not-
operator, toggles true to false and false to
true. Another way to write the above is:
val alsoTrue = !(1 == 2)
After evaluating first subexpression, it’s not need to evaluate last one,
because all result is determined. This called “short-circuit evaluation”
String equality
• Sometimes you want to determine if two strings
are equal.
• For example, a children’s game of naming an
animal in a photo would need to determine if the
player answered correctly.
• In Kotlin, you can compare strings using the
standard equality operator “==“ in exactly the
same way as you compare numbers. For example:
val guess = "dog"
val dogEqualsCat = guess == "cat"
String comparision
• Just as with numbers, you can compare not
just for equality, but also to determine if one
value is greater than or less that another
value. For example:
val order = "cat" < "dog"
val hourOfDay = 12
val timeOfDay: String
timeOfDay = when (hourOfDay) {
0, 1, 2, 3, 4, 5 -> "Early morning"
6, 7, 8, 9, 10, 11 -> "Morning"
12, 13, 14, 15, 16 -> "Afternoon"
17, 18, 19 -> "Evening"
20, 21, 22, 23 -> "Late evening"
else -> "INVALID HOUR!"
}
println(timeOfDay)
Ranges
• Before you dive into the when expression, you
need to know about the range data types,
which let you represent a sequence of
countable integers.
• Let’s look at two types of ranges.
• First, there’s a closed range, which you
represent like so:
val closedRange = 0..5
The two dots (..) indicate that this range is closed, which means the
range goes from 0 to 5 inclusive. That’s the numbers (0, 1, 2, 3, 4, 5).
Ranges
• Second, there’s a half-open range, which you
represent like so:
val halfOpenRange = 0 until 5