Functions
Declarations, defaults, and single-expression form.
1. Declaring a function
Functions use fun. Each parameter has a type, and the return type follows the parameter list:
fun add(a: Int, b: Int): Int {
return a + b
}
add(2, 3) // 5
Functions can be called from anywhere main can reach them. They're typed end-to-end — the compiler will yell if you pass a String where it expects an Int.
2. Declare add
Write the entire function from scratch this time — no starter scaffold. Declare add so it takes two Int parameters and returns their sum.
Reminder of the shape from the previous step:
fun NAME(p1: TYPE, p2: TYPE): RETURN_TYPE {
return ...
}
Starter code
// Declare your add function below.
// It should take two Int parameters and return their sum.
3. Default and named arguments
Parameters can have defaults — callers can omit them:
fun greet(name: String, excited: Boolean = false): String =
if (excited) "Hi, $name!" else "Hi, $name."
greet("Ada") // "Hi, Ada."
greet("Bob", true) // "Hi, Bob!"
You can also pass arguments by name — much clearer at the call site:
greet(name = "Eve", excited = true) // "Hi, Eve!"
Named arguments are great when a function takes booleans or several similar parameters.
4. Default arguments
Two things to do this time:
- Give the
excitedparameter a default value offalse(so callers can omit it). The harness callsgreet("Ada")with no second argument — without a default, that won't even compile. - Implement the body:
excited = true→"Hello, NAME!"excited = false(the default) →"Hello, NAME."
Reminder of the syntax:
fun foo(x: Int, flag: Boolean = false): String { ... }
Starter code
// Add a default value of `false` to `excited` so callers can call greet("Ada"),
// then fill in the body.
fun greet(name: String, excited: Boolean): String {
return ""
}5. Single-expression form
When the body is a single expression, you can drop the braces and the return keyword. The function uses = instead:
fun double(x: Int): Int = x * 2
fun isOdd(n: Int) = n % 2 != 0 // return type inferred
This is idiomatic for short helpers, especially predicates and small calculations.
6. Single-expression isEven
Convert isEven to single-expression form returning n % 2 == 0. Replace the function body entirely with = n % 2 == 0.
Starter code
fun isEven(n: Int): Boolean = falseRun this Kotlin lesson in your browser
SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.
Sign in to run this code →