Basic Functions
Learn how to modularize chunks of code into functions and how to call your functions in Kotlin. Understand the difference between function signatures and function declarations.
Functions separate useful chunks of code into a named entity you can reference in your code. Along with variables, they are the absolute fundamental language construct to avoid code duplication.
Function Signatures #
A function signature defines a function’s name, inputs, and outputs. In Kotlin, it looks like this:
fun fibonacci(index: Int): Long
This signature defines a function named fibonacci
with one input parameter named index
of type Int
and a return value of type Long
. In other words, you give the function an integer and get back a Long
. This function implements the well-known Fibonacci sequence.
Declaring a Function #
In a function declaration, both a function signature and a function body are required:
fun fibonacci(index: Int): Long {return if (index < 2) {1} else {fibonacci(index-2) + fibonacci(index-1) // Calls `fibonacci` recursively}}
The ...