Instruction
What Is a Function?
A function is a block of code that performs a specific task. Whenever your app needs to execute the task, you call the function.
Kotlin includes two types of functions: predefined and user-defined functions.
Predefined Functions
These are functions provided by the Kotlin standard library. They’re readily available for use. For example, println() :
fun main() {
println("Hello Kotlin!!")
}
This code prints “Hello Kotlin!!” to the screen, like this:
Hello Kotlin!!
The max() function provided in the Math package compares two numbers and returns the larger one.
import kotlin.math.max
fun main() {
val largest = max(3, 4)
println("The largest number is $largest.")
}
max() takes two parameters of type Int. In the example above, the values 3 and 4 are passed as arguments.
You’ll learn more about parameters in the upcoming lessons.
The code above prints the following to the screen:
The largest number is 4.
You’ve now learned some basics about functions in Kotlin. In the next section, you’ll learn how to create user-defined functions.