Interactive Kotlin Basics

romainbsl
2,120 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

IF ... as an expression

Classic IF statement

1
2
3
4
5
6
7
8
fun max(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In Kotlin, IF becomes an expression, that means that it cans return values

1
2
3
fun max(a: Int, b: Int) = if (a > b) a else b
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

WHEN expression

You can use when to evaluate objects.

1
2
3
4
5
6
7
8
9
fun describe(obj: Any): String =
when (obj) {
is Dog -> "This is a dog: $obj, his weight is ${obj.weight}"
is Cat -> "This is a cat: $obj, his color is ${obj.color}"
is Animal -> "This is an aniaml: $obj"
else -> "Unknown"
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content