KOTLIN / CHAPTER 01
Values and functions
BeginnerExpress small computations with typed parameters and returned values.
By the end of this chapter
- Distinguish val from var
- Read inferred types
- Write an expression-bodied function
The idea
Kotlin uses val for a binding that cannot be reassigned and var for one that can. Type inference often lets the compiler determine the type from the initializer, but the resulting type still constrains later operations. A val that refers to a mutable object does not freeze that object. Distinguish changing a binding from changing the state accessible through it.
Functions declare named parameters and can return a value. An expression-bodied function uses an equals sign when a single expression supplies the result. String templates embed values or expressions in text. Keep calculation separate from printing when another function may need the result, and state assumptions such as nonzero divisors or bounded integer inputs.
fun label(name: String, count: Int) = "$name: ${count + 1}"
fun main() {
val count = 4
println(label("Tasks", count))
println(count)
}Tasks: 5 4
The function computes a new string from its parameters. Its arithmetic does not reassign the caller’s count binding.
Try it yourself
Write a function returning a label for a project and a completed-task count.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING