In the previous lessons, we have written functions with no return type. Such a function returns Unit, Kotlin's way of saying it is not returning any useful value.
It's also possible to return a value from a function. For this, we need to specify the return type of the function after the parameter list, following a colon.
Inside the function, we can use the return statement to send a value back out of a function.
The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):
fun plusThree(num: Int): Int {
return num + 3
}
// Inside main function:
val answer = plusThree(5)
println(answer) // Output: 8
Here, we have declared the return type Int. This means that the function returns an Int value.
plusThree takes an Int argument for num and returns an Int value equal to num + 3.
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
