Kotlin Single Expression Functions
Published:
Consider the following Kotlin function examples:
```
// Regular function
fun sum(a: Int, b: Int): Int {
return a + b
}
// Single expression function
fun sum(a: Int, b: Int): Int =
```
Identify the feature used in the second function.
Choose one of the following.
○ Simplified Formatting
This question includes visual content: A code snippet block displaying two Kotlin function definitions. The first is a regular function using curly braces and a return statement. The second is an incomplete 'single expression function' defined using an equals sign. The rest of the image includes text describing the task.
Animated Video Solution
The first half plays free, the full solution is in the app.
Step by Step Written Solution
In this problem, we are looking at two ways to define the same function in Kotlin and identifying the specific feature used in the second example.
Kotlin Function Syntax
The first example shows a regular function definition. It uses curly braces to define a block of code and an explicit return keyword to yield the result.
1. Regular Function
```kotlin
fun sum(a: Int, b: Int): Int {
return a + b
}
```
Now look at the second example. Instead of using curly braces and a return statement, it uses an equals sign followed by the expression.
2. The Second Example
```kotlin
fun sum(a: Int, b: Int): Int = a + b
```
The rest of this solution is on Solvi
2 more steps are locked. Watch the full animated, narrated solution for free.
Snap a photo, solve any question like this.
Watch the Rest for FreeFree to download · First solutions are on us