Menengah Exercism • kotlin

Conditionals

Ringkasan Pelajaran

# Introduction

About conditionals

Comparison operators

Comparison operators are similar to many other languages, with a few extensions.

For equality, the operators are == (equal) and != (not equal).

val txt = "abc"
txt == "abc" // => true
txt != "abc" // => false

Additionally, the === and !== operators test for “referential equality”: a === b if and only if a and b point to the same object. This should make more sense later in the syllabus.

The greater/less than operators are also conventional.

1 < 3 // => true
3 > 3 // => false
3 <= 3 // => true
4 >= 3 // => true

Branching with if

This is the full form of an if expression:

if (conditional1) {
//    something...
} else if (conditional2) {
//    something...
} else {
//    something...
}
  • Parentheses () around each conditional are required.
  • A conditional must evaluate to a Boolean true or false. Kotlin has no concept of “truthy” and “falsy” as found in some languages.
  • Braces {} are optional, if there is only a single expression.
  • Both else if and else are optional, and there can be multiple else if blocks.

Alternatives?

By deliberate choice, Kotlin does not have the ternary operator ? : found in Java. A concise form of if ... else is preferred:

val result = if (isOk) goodValue else badValue

return if (isOK) goodValue else badValue

Unlike Ruby, the concise if ... else form always needs an else and thus cannot be used as a guard statement:

return 42 if (isOk)
// Syntax error: Unexpected tokens (use ';' to separate expressions on the same line).
// Syntax error: Expecting an expression.

return if (isOk) true
// 'if' must have both main and 'else' branches when used as an expression.

Note that in Kotlin, if is an expression returning a value. It is not a statement as in Java.

We will see in a later Concept that Kotlin has a powerful when construct, intended to replace long chains of else if clauses with pattern matching.


Originally from Exercism kotlin concepts