Kotlin Single-Expression Function
Kotlin single-expression function is a function where a single expression is assigned to the function, and the expression’s evaluated value is returned when this function is called.
The syntax of Kotlin Single-Expression Function is
</>
Copy
fun functionName(parameters) = expression
The expression’s value is returned to the function call.
Examples
In the following Kotlin program, we write a single-expression function rectArea
to compute the area of rectangle, given length and breadth as parameters.
Main.kt
</>
Copy
fun rectArea(length: Int, breadth: Int) = length * breadth
fun main(args: Array<String>) {
val length = 5
val breadth = 4
val area = rectArea(length, breadth)
print("Area of the rectangle is $area units.")
}
Output
Area of the rectangle is 20 units.
In the following Kotlin program, we write a single-expression function greet
to return a greeting String.
Main.kt
</>
Copy
fun greet(name: String) = "Hello $name"
fun main(args: Array<String>) {
val greeting = greet("Tesla")
print(greeting)
}
Output
Hello Tesla
Conclusion
In this Kotlin Tutorial, we learned how to write a single-expression function in Kotlin, with the help of examples.