Functions

A function is a reusable block of code that performs a specific task

You can pass data, known as parameters, into a function

Functions help you organize and reuse code by defining logic once and calling it multiple times

Use the func keyword to declare a function

Create a function

func functionName() { // code to be executed }

Example

func greet() { println("Hello world") } greet()

Parameters

You can pass parameters into a function

func functionName(parameter1: type, parameter2: type, ...) { // code to be executed }

Function parameters are immutable by default

Example

func greet(name: String) { println("Hello " + name) //name = "hi" wrong because parameters are immutable } greet("John")

Return value

If a function returns a value, you must declare its return type

func functionName(parameter1: type, parameter2: type, ...): type { // code to be executed }

Use the return keyword to return a value

func add(a: Int, b: Int): Int { return a + b } val result = add(3, 5) println(result) //>> 8

Single-expression function

If a function contains only a single expression, you can use the shorthand syntax.

The expression result will be returned automatically.

func functionName(parameter1: type, parameter2: type, ...) = expression func functionName(parameter1: type, parameter2: type, ...): type = expression

Example

func plus(a: Int, b: Int): Int = a + b println(plus(2, 3)) //>> 5