Kotlin Functions

Kotlin Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are important for reusing code.


Creating and Calling a Function

To create your own function, use the fun keyword, followed by the name of the function, and parentheses (). To call the function, write the function's name followed by parentheses.

Example

fun myFunction() {
  println("I just got executed!")
}

fun main() { myFunction() // Calling the function }


Function Parameters and Return Values

Functions can take input variables (parameters) and can also return a result back to whoever called them. You must specify the data type of the return value after the parentheses using a colon :.

Return Value Example

// Takes two Int parameters, and returns an Int
fun addNumbers(x: Int, y: Int): Int {
  return x + y
}

fun main() { println(addNumbers(5, 3)) // Outputs 8 }