In Kotlin the ends return
statement executes a function and, if present, returns a value to the caller. Here is an example of using the return statement:
fun main() {
val result = sumOfNumbers(5, 3) // result = 8
println(result)
}
fun sumOfNumbers(number1: Int, number2: Int): Int {
return number1 + number2
}
When a function uses the return statement to return a value, the return type of the function must be explicitly specified. The return type is defined after the list of parameters and the colon. In the example above, the return type was Int used. Here are more examples of different return types in Kotlin:
// Beispiel für Rückgabetyp Boolean
fun main() {
val result1 = isEven(10) // result1 = 'true'
println(result1)
val result2 = isEven(11) // result2 = 'false'
println(result2)
}
fun isEven(numberToCheck: Int): Boolean {
return numberToCheck % 2 == 0
}
// Beispiel für Rückgabetyp String
fun main() {
val output = userGreeting("Duffy")
println(output)
}
fun userGreeting(userName: String): String {
return "Hello, $userName!"
}
Return type Unit
A function that returns no result implicitly returns a value of type Unit back. This guy is comparable to that void-Type used in some programming languages to indicate no return. The following function shows an example of this:
// Beispiel für Rückgabetyp Unit
fun main() {
helloWorld()
}
fun helloWorld() {
println("Hello World!")
}
The function shown above corresponds to the following function:
// Beispiel für Rückgabetyp Unit
fun main() {
helloWorld()
}
fun helloWorld(): Unit { // Hier wurde explizit der Rückgabewert angegeben
println("Hello World!")
}
Even in cases where a function has the return type Unit
can still do that return-Statement can be used to terminate the function early without returning a value. This approach is beneficial for completing a function in a timely manner and avoiding unnecessary statements, which ultimately optimizes the performance of the code.
- Example – Exiting a function when a condition is met:
fun main() {
checkNumber(-5) // Ausgabe: Negative Zahl
checkNumber(3) // Ausgabe: Positive Zahl oder Null
}
fun checkNumber(numberToChek: Int) {
if (numberToChek < 0) {
println("$numberToChek is a negative number")
return
}
println("$numberToChek is a positive number")
}
- Example – exiting a function within a loop:
fun main() {
findFirstEven(intArrayOf(1, 3, 5, 7, 8, 9)) // Ausgabe: Die erste gerade Zahl ist 8
findFirstEven(intArrayOf(1, 3, 5, 7, 9)) // Ausgabe: Es wurden keine geraden Zahlen gefunden
}
fun findFirstEven(numbersToCheck: IntArray) {
for (number in numbersToCheck) {
if (number % 2 == 0) {
println("The first even number is $number")
return
}
}
println("No even numbers were found")
}