Functions in Kotlin
Contents
In this post, I aim to summarize the essential aspects of function syntax in Kotlin. While this post touches upon some commonly used functionalities, especially in Android development, it doesn’t delve deep into the advanced usages.
Regular Functions
Regular functions are the basic building blocks. Here’s a simple function that compares the lengths of two strings:
|
|
It’s necessary to specify the types of parameters. However, the return type can often be inferred by the compiler.
Default Arguments
Functions can have default values for their parameters. For instance:
|
|
This allows you to call the function as `compare()` or `compare(“hi”, “hello”)`.
Single-expression Functions
For functions comprising just a single expression, you can drop the curly braces and use the `=` symbol:
|
|
Moreover, if the compiler can infer the return type, you can omit it:
|
|
Generic Functions
Generics enable functions to operate on different data types, ensuring code reusability and type safety.
|
|
Lambdas
In Kotlin, functions are first-class, meaning they can be stored in variables, passed around, and returned from other functions.
Defining Function Types
Function types can be defined similar to other types:
|
|
Here, `onClick` is a variable of a function type. This function takes no arguments and returns `Unit` (similar to `void` in other languages).
Lambda Expressions
Lambda expressions, or simply lambdas, represent small chunks of code. They can be used primarily to define inline functions. The syntax is concise:
|
|
In this lambda:
- The expression is enclosed in curly braces.
- The parameter types can be omitted if they can be inferred.
- The lambda body follows the `->` symbol.
- If the return type isn’t `Unit`, the last expression is taken as the return value.
Trailing Lambdas
A nifty Kotlin feature is the ability to move lambdas out of parentheses if they’re the last argument in a function call:
|
|
Author Jeffery@slc
LastMod 2023-10-10