Lesson contents

Kotlin — Functions, return types, and require

A Kotlin function declares its parameters and can declare its return type. Use require to reject invalid arguments before calculating the result.

A simple example

Call a function with 2

  1. Start with Argument 2
  2. Do this Double the argument
  3. Result 4
The function receives 2, adds it to itself and returns 4 to its caller.
Lesson.kt
fun twice(n: Int): Int = n + n
fun main() {
    println(twice(2))
}
Output
4
Advertisements

Calculate how many boxes an order needs

Parameters are read-only inside the function. require checks the input contract and throws IllegalArgumentException on failure. An if expression supplies the extra zero or one.

Books to send: 17. Capacity: 8 per carton. Cartons needed: 3.
Choose cartons for a book order

A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
fun boxesNeeded(items: Int, capacity: Int): Int {
    require(items >= 0 && capacity > 0)
    return items / capacity + if (items % capacity == 0) 0 else 1
}

fun main() {
    println(boxesNeeded(17, 8))
    println(boxesNeeded(16, 8))
}
Output
3
2

The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.

Try it yourself

How many boxes do zero items need?

Check your answer

Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.

Kotlin language documentation

Related tags

  • Kotlin
  • functions
  • parameters
  • return values