Kotlin Starter Pack

romainbsl
2,779 views

Open Source Your Knowledge, Become a Contributor

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

Create Content

In this section you'll find some basics syntax to start coding with Kotlin.

Variables

Kotlin provides two way to declare variable.

  • Immutable (read-only) variable:

Using the keyword valmeans that your variable could be assign just once.

immediate assignment

val a: Int = 1

variable's type can be inferred

val b = 2 // `Int`

deferred assignment

val c: Int  // type is required when there is no initializer
c = 3
  • Mutable (read/write) variable:

Using the keyword var allow you to declare mutable variables.

1
4
5
6
// {...}
var x = 5 // `Int` type is inferred
x += 1 // x now is equals to 6
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

String templates

String are made easier with Kotlin, more convinient to use, and more readable.

Simple templates

1
4
5
6
7
// {...}
var name = "Kotlin"
// simple name in template:
val str = "Hello, $name !" // prints "Hello, Kotlin !"
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Here is a more interesting part. You may be able to invoke piece of code inside a template, avoiding lots of boilerplate code.

String manipulation

1
4
5
6
7
8
9
10
// {...}
val name = "Kotlin"
// simple template
val str = "Hello, $name !"
// using expression in template:
val str2 = "${str.replace("Hello", "Welcome on this playground")}"
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Math expression

1
4
5
6
7
8
9
10
11
// {...}
val left = 2
val right = 5
val sum = "+ of $left and $right gives: ${left + right}"
val sum2 = "+ of squared $left and $right gives: ${Math.pow(left.toDouble(), 2.0) + Math.pow(right.toDouble(), 2.0)}"
val multiply = "* of $left and $right gives: ${left * right}"
val div = "/ of $left and $right gives: ${left / right}"
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Control expressions

if statement becomes an expression

To compare two values, you would write the following code

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 can be an expression, that means that you can assign a variable or return the if directly. Previous snippet can be write as follow.

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

Or, in idiomatic Kotlin (c.f. part 3. on Functions)

fun max(a: Int, b: Int) = if (a > b) a else b
when expression

If you were familiar to the switch statement from other language like Java, you won't find it in Kotlin. It has been replaced by the when expression.

You can use when to evaluate objects and return a result.

1
2
3
4
5
6
7
8
9
fun sayHello(language: String) {
println(when (language) {
"EN" -> "Hello!"
"FR" -> "Salut!"
"IT" -> "Ciao!"
else -> "Sorry, I can't greet you in $language yet"
})
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

To go further, when allow you to make some condition by mixing values, ranges, Types, etc. The when expression will try to match with every branches sequentially and stop at the first satisfied condition.

1
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fun describe(obj: Any) {...}
// { autofold
abstract class Animal(val name: String) {
override fun toString(): String {
return "${this.javaClass}(name='$name')"
}
}
class Dog(name: String, val weight: Double) : Animal(name)
class Cat(name: String, val color: String) : Animal(name)
class Snake(name: String) : Animal(name)
fun main(args: Array<String>) {
describe("EN")
describe(0)
describe(2)
describe(4)
describe(Dog("Rex", 9.2))
describe(Cat("Felix", "White"))
describe(Snake("Dr Snake"))
}
// }
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

A third one, you can use when without any input value, like in this snippet.

when {
  obj1 is Person -> goToRestaurant()
  obj2 is Animal -> feedTheDog()
}

Loops

For loops

for works on anything that's iterable. You may think of it as a foreach, like in Java's lambda or C#.

1
4
5
6
7
8
// {...}
val animals = listOf("dog", "cat", "snake")
for (aniaml in animals) {
println(aniaml)
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

A combination of Kotlin's features, makes for even more convinient. By desctructuring we can iterate over a collection with indexes:

1
4
5
6
7
8
// {...}
val animals = listOf("dog", "cat", "snake")
for ((animal, index) in animals.withIndex()) {
println("animal at $index is $animal")
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
While loops

while works as in many languages

1
4
5
6
7
8
9
10
// {...}
val aniamls = listOf("dog", "cat", "snake")
var index = 0
while (index < aniamls.size) {
println("animal at $index is ${aniamls[index]}")
index++
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content