Released · improving
Kotlin guide · 2/6
This chapter covers the syntax you will use every day: variables, functions, conditionals, loops, and string templates. With these in hand you can already write useful small programs.
val declares a read-only variable that cannot be reassigned; var declares one that can. Idiomatic Kotlin reaches for val first and uses var only when a value really has to change. Types are usually inferred, so you can leave them out.
const val MAX_USERS = 100 // compile-time constant, top level or inside an object
fun main() {
val language = "Kotlin" // inferred as String
var count: Int = 0 // or spell out the type
count += 1
// language = "Java" // error: val cannot be reassigned
println("$language $count / $MAX_USERS")
}Note that val fixes the reference, not the object. With val list = mutableListOf(1), calling list.add(2) is perfectly legal.
Functions start with fun; parameter and return types follow a colon. When the body is a single expression, replace the braces with = and let the compiler infer the return type.
fun add(a: Int, b: Int): Int {
return a + b
}
fun square(x: Int) = x * x // expression body, returns Int
fun greet(name: String, greeting: String = "Hello", mark: Char = '!'): String =
"$greeting, $name$mark"
fun main() {
println(add(2, 3)) // 5
println(square(4)) // 16
println(greet("Sam")) // Hello, Sam!
println(greet("Ana", greeting = "Hi")) // Hi, Ana!
println(greet(mark = '?', name = "Lee")) // Hello, Lee?
}Parameters with default values can be skipped, and named arguments let you pass only what you need in any order. That removes most of the overload boilerplate common in Java. A function that returns nothing useful has the return type Unit, which you normally omit.
if produces a value, which is why Kotlin has no ternary operator: you assign the result of if directly.
fun describe(score: Int): String {
val passed = if (score >= 60) "pass" else "fail"
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
else -> "F"
}
return "$passed ($grade)"
}
fun kind(x: Any): String = when (x) {
0, 1 -> "zero or one"
in 2..9 -> "a single digit"
is String -> "a string of length ${x.length}"
else -> "something else"
}when replaces Java's switch. Given a subject, branches can match values, ranges (in) or types (is). Without a subject it behaves like an if-else chain, testing conditions top to bottom. Used as an expression it must cover every case, so you usually need an else branch. Being able to call x.length inside the is String branch is a smart cast, explained in chapter 6.
Embed values with $name or arbitrary expressions with ${...}. Raw strings use triple quotes, and trimIndent() strips the common leading indentation.
fun main() {
val user = "Ana"
val items = listOf("apple", "pear")
println("$user has ${items.size} items in the cart")
println("Total: ${items.size * 3} dollars")
val json = """
{
"name": "$user",
"count": ${items.size}
}
""".trimIndent()
println(json)
}There is no C-style for (i = 0; i < n; i++). Instead, for ... in iterates over ranges and collections.
| Expression | Meaning | Values |
|---|---|---|
1..5 | closed range | 1, 2, 3, 4, 5 |
0..<5 | end excluded, same as 0 until 5 | 0, 1, 2, 3, 4 |
10 downTo 0 step 3 | counting down by 3 | 10, 7, 4, 1 |
'a'..'e' | character range | a, b, c, d, e |
fun main() {
for (i in 1..5) print("$i ")
println()
for (i in 10 downTo 0 step 3) print("$i ")
println()
val fruits = listOf("apple", "pear", "grape")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
var n = 3
while (n > 0) {
println("$n left")
n--
}
repeat(2) { println("round $it") }
outer@ for (x in 1..3) {
for (y in 1..3) {
if (x * y == 4) break@outer // leaves both loops
println("$x x $y")
}
}
}Ranges also work in membership checks such as if (age in 20..29). To break out of an outer loop, label it (outer@) and use break@outer.
val; use var only for values that must change.=.if and when are expressions; when can match values, ranges and types.$name and ${expression} templates.for ... in over ranges like 1..5, 0..<n, downTo and step, or over collections.
0 comments
Sign in · Sign in to leave a comment.
Be the first to comment.