Tuesday 30 July 2019

Kotlin : Function (Post 4)

Hi All,

In previous post , I discussed about the control flow in Kotlin. Now continuing the basics in Kotlin , here in this post we will discuss about how functions are declared and called in this language.

=> Functions are used "fun" keyword to declare it.

=> Here I am showing how user define functions are defined in it.

Simple function example :


fun sayHello(){
Log.d(TAG,"Hello")
}

Output:
Hello
----------------------------------------------------------------

Parameterize Function and Return Value :


fun sum(num1 : Int , num2 : Int) :Int {
return num1+num2
}


calling the function : var num3 = sum(a,b)

Output:
Sum of two numbers:8
------------------------------------------------------------------

Named Parameters :

In kotlin we can have  the named parameter , let's take a look how we declare these type of functions:


  findVolumn(height =6, length =4 , width =5 )

And function body like :

  private fun findVolumn(length: Int, width: Int, height: Int) {

        println("Length is:"+length)
        println("Width is:"+width)
        println("Height is :"+height)
    }

Output:
Length is:4
Width is:5
Height is :6

Here , in named parameter we can see , that with the help of name of that parameter , whatever the order of the argument , it will use on the basis of its names. 

Benefit of this type of parameter is , with the help of parameters names , safer side function will handle the actual argument , so this will prevent any mistake by defining the values right & clear.

That's all for this post, I will update more types of functions in Kotlin in my future posts.








No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...