Twitter LogoFacebook Logo
Placing code into separate blocks.
By: King

A Function is a feature that allows you to group and name a set of computer instructions so that it can be "called" to execute the instructions inside. You can pass data into functions and they can return data as a result.


fun [name] () : [return type] {


In Kotlin, a function is defined using the def keyword. Following afterwards, there will be (1) the name, (2) open and close parenthesis so we can pass data into the function, and (3) the return type.


fun printMessage(): Unit {
    println("Hello, welcome to")

In the example:

The "fun" keywords lets the computer know that there is a function declaration.

The function is called "printMessage."

The "Unit" return type means that the function returns no value. The purpose is to execute the code inside the curly brackets.

Functions that returns a value

fun onePlusOne(): Int {
    return 1 + 1

In the above code, there is a function that returns an Int (integer) value. A function that has a return type other than "Unit," must contain the "return" statement somewhere inside the function.

Functions with parameters

Sometimes you may want to bring values into the function so your function can be reused for some purpose.

In the example earlier, there is a function call onePlusOne() that returns 2 (1 + 1) back when we call it.

Instead of only returning 2, we can make the function return a result other than 1 + 1. For example:

fun onePlusOne(a: Int, b: Int): Int {
    return a + b

There are 2 places that changed for the function onePlusOne. Inside the parenthesis (), we added:

a: Int, b: Int

This is saying that the function can take in 2 integers.

Another thing that was change was the return statement:

return a + b

Instead of returning 1 + 1, we are returning the combined result of a & b. This makes the function more useful and can be used to add any 2 numbers.

Using "Calling" Functions

To call a function, just type the name of the function followed by parenthesis.


For functions with parameters, we must pass in "arguments" (values) to fulfill what the function needs to be used.

onePlusOne(5, 10)

Since the onePlusOne function was modified to accept 2 values, we must provide it in order to call the function. 

The value that is returned from a function can be store in a variable or be used in another function as an "argument."

var result = onePlusOne(5, 10)

var result = onePlusOne(onePlusOne(20, 40), 10)

In the first example, it is storing 5 + 10 in the result variable.

In the second example, it is calling the onePlusOne function inside the parenthesis of the outer onePlusOne function.

The inner function will be executed first and then the value will be used in the outer function. So it'll get 20 + 40 (60) and then 60 + 10 (70). 

Sign In