Functions as a expression in Kotlin

Functions as a expression in Kotlin

In this blog, we will look at how we can use function as a expression to return value from it. Here is a traditional function to get the maximum numbers between two numbers

fun main() {
        println("Max number is "+max(4,5))
}

fun max(num1:Int, num2:Int):Int{

    if(num1>=num2){
        return  num1
    }else{
        return num2
    }

}

However, kotlin provides more expressive way to do this

fun main() {
        println("Max number is "+max(4,5))
}

fun max(num1:Int, num2:Int):Int = if(num1>=num2)num1 else num2 

That’s it 😀

Here, function max will return the last statement as a expression. For example,

fun main() {
        println("Max number is "+max(4,5))
}

fun max(num1:Int, num2:Int):Int = if(num1>=num2) {
                                            num1
                                            25
                                    } else{
                                        num2
                                        50
                                    }

In this, case, 25 will be returned if num1 is greater otherwise 5o will be returned.

Leave a Reply

Your email address will not be published. Required fields are marked *