- Explain the difference between
valandvar - Use the types
Int,Long,Double,Boolean,CharandString - Do arithmetic and convert between types
- Write string templates with
$and${}
A game on your phone remembers your name, your points, your level and whether the sound is on. These are different kinds of data: text, a whole number, a yes/no answer. A program keeps such data in variables, and Kotlin carefully tracks the type of every variable so that you never divide a piece of text by a number by mistake.
val and var
In Kotlin a variable is created with one of two words. val (value) is a read-only variable: it gets a value once and cannot be changed afterwards. var (variable) can receive a new value at any time. The = sign assigns a value.
fun main() {
val name = "Aysel"
var score = 10
println(name)
println(score)
score = score + 5
score += 3
println(score)
}Aysel 10 18
score += 3 means score = score + 3.Basic types and type inference
| Type | Example | What it stores |
|---|---|---|
Int | 15, -3 | whole numbers (about ±2.1 billion) |
Long | 8_000_000_000L | very large whole numbers |
Double | 3.14, 2.5 | numbers with a fractional part |
Boolean | true, false | true or false |
Char | 'A' | a single character, in single quotes |
String | "Baku" | text, in double quotes |
You do not have to write the type every time: when you write val age = 15, the compiler works out by itself that age is an Int. This is called type inference. If you like, you can also state the type explicitly after a colon: val age: Int = 15. To make big numbers easier to read, you can separate digits with underscores: 1_000_000.
fun main() {
val age: Int = 15
val height = 1.62
val isStudent = true
val grade = 'A'
val worldPopulation = 8_000_000_000L
println(age)
println(height)
println(isStudent)
println(grade)
println(worldPopulation)
}15 1.62 true A 8000000000
Int, so the L at the end makes it a Long.Arithmetic and type conversion
Kotlin has the operators +, -, *, / and %, which gives the remainder. Watch out: dividing two Int values also gives an Int, and the fractional part is dropped — 7 / 2 gives 3. If you need a fractional result, one of the numbers must be a Double. Kotlin never converts types on its own; you do it explicitly with functions such as toInt(), toDouble() and toString().
fun main() {
val apples = 7
val kids = 2
println(apples / kids)
println(apples % kids)
println(apples / 2.0)
println(apples.toDouble() / kids)
val price = "25".toInt()
println(price * 2)
println(9.99.toInt())
}3 1 3.5 3.5 50 9
toInt() does not round, it simply drops the fractional part: 9.99 → 9.Strings and templates
You can glue text together with +, but Kotlin has a more convenient way — string templates. Inside a string you write $ followed by a variable name, and its value is inserted automatically. For a whole expression, use curly braces: ${age + 1}.
fun main() {
val name = "Murad"
val city = "Baku"
val age = 14
println("$name lives in $city.")
println("Next year $name will be ${age + 1}.")
println("The name has ${name.length} letters.")
println("Hello, " + name + "!")
}Murad lives in Baku. Next year Murad will be 15. The name has 5 letters. Hello, Murad!
Strings come with many useful functions. length gives the length, [0] takes the first character (counting starts at zero), and uppercase() and lowercase() change the letter case:
fun main() {
val word = "Kotlin"
println(word.length)
println(word.uppercase())
println(word.lowercase())
println(word[0])
println(word.last())
println(word.contains("lin"))
println(word.reversed())
println("ha".repeat(3))
println(" hello ".trim() + "!")
}6 KOTLIN kotlin K n true niltoK hahaha hello!
Key points
valis read-only, whilevarcan be reassigned; prefervalwhenever you can.- The compiler infers the type from the value:
val x = 2.5is aDouble. - Dividing two
Intvalues gives anInt(7 / 2=3);%gives the remainder. - Types are not converted automatically: use
toInt(),toDouble(),toString(). - String templates:
"$name"inserts a variable and"${a + b}"inserts an expression.
Check yourself
10 questions. Every correct answer earns XP.