Learn/Kotlin/6. Functions
Lesson 6 of 8
Sign in

Kotlin, lesson 6

Functions

You have been writing one function all along: main. Writing your own functions lets you give a name to a piece of work, reuse it as often as you like, and test it on its own. A program built from small, well-named functions is much easier to read than one long main.

Declaring a function

Read the first line piece by piece:

  • fun tip declares a function named tip.
  • (bill: Double, percent: Int) lists its parameters. Each one needs a name and a type; Kotlin does not guess parameter types.
  • : Double after the parentheses is the return type, the kind of value it hands back.
  • return ends the function and sends the value back to whoever it.

2 exercises to try what you just read.

Exercise 1

Letter grades

Press Ctrl Enter or Check to test your code.

Exercise 2

Room painter

Press Ctrl Enter or Check to test your code.

called

The values you pass in a call, like 40.0 and 15, are called arguments. Functions can be declared before or after main in the file; the order doesn't matter.

Functions that just do something

If a function doesn't return a useful value, leave out the return type. It then returns Unit, Kotlin's way of saying "nothing interesting".

Single-expression functions

When the whole body is one expression, you can drop the braces and return and write = instead. Kotlin works out the return type for you:

This short form is very common in Kotlin code for small helper functions.

Default and named arguments

A parameter can have a default value, used when the caller leaves that argument out. And any argument can be passed by name, which makes calls self-explanatory:

Parameters are read-only

Inside the function, parameters behave like vals: you can read them but not reassign them. If you need a changing value, copy it into a local var first.

Scope

A variable declared inside a function (or inside any { } block) exists only within those braces. That region is its scope. Two functions can each have a variable called total and they never interfere. To share information between functions, pass it in as an argument and hand it back as a return value, rather than reaching for variables outside.

Further reading

  • Kotlin docs: Functions
  • Kotlin docs: Basic syntax, functions

Write the function letterGrade(score: Int): Char that turns a test score from 0 to 100 into a letter:

  • 90 and above: 'A'
  • 80 to 89: 'B'
  • 70 to 79: 'C'
  • 60 to 69: 'D'
  • below 60: 'F'

Your code is placed above a hidden main that reads a line of scores separated by spaces, calls your function for each one, and prints the letters separated by spaces. For example, the input 95 82 40 prints A B F. You only write the function.

You are painting rooms. Write a program with a function wallArea(length: Int, width: Int, height: Int = 3): Int that returns the area of the four walls of a room: 2 * (length + width) * height.

Input: the first line holds the number of rooms n. Each of the next n lines holds a room's length and width, and sometimes a third number for the height. When the height is missing, use the default of 3.

Output: one line per room, Room <number>: <area>, then a final line Total: <sum>.

Sample input:

Sample output:

Hint: after split(" "), check the list's size to see whether a height was given.

fun tip(bill: Double, percent: Int): Double {
    return bill * percent / 100
}

fun main() {
    println(tip(40.0, 15))   // 6.0
    println(tip(12.5, 20))   // 2.5
}
fun printDivider(width: Int) {
    println("-".repeat(width))
}
fun square(n: Int) = n * n
fun isEven(n: Int) = n % 2 == 0
fun greet(name: String, greeting: String = "Hello", times: Int = 1) {
    repeat(times) { println("$greeting, $name!") }
}

fun main() {
    greet("Sam")                         // Hello, Sam!
    greet("Sam", "Welcome")              // Welcome, Sam!
    greet("Sam", times = 2)              // Hello, Sam! (twice)
}
fun average(a: Int, b: Int): Double {
    val sum = a + b          // sum lives only inside average
    return sum / 2.0
}
2
4 3
5 5 2
Room 1: 42
Room 2: 40
Total: 82