Thursday, 1 February 2018

Kotlin: Single Expression functions

When a function returns single expression, you can omit curly braces.

Ex
fun square(num: Int) = num * num
fun cube(num: Int) = num * num * num

FunctionDemo.kt
fun square(num: Int) = num * num
fun cube(num: Int) = num * num * num

fun main(args: Array<String>) {
 println("Square of 5 is ${square(5)}")
 println("Cube of 5 is ${cube(5)}")
}

Output
Square of 5 is 25
Cube of 5 is 125



Previous                                                 Next                                                 Home

No comments:

Post a Comment