In Kotlin the ends returnstatement executes a function and, if present, returns a value to the caller. Here is an example of using the return statement:

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:

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:

The function shown above corresponds to the following function:

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.

  1. Example – Exiting a function when a condition is met:
  1. Example – exiting a function within a loop:

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked