Open In App

Kotlin Function Variations With Examples

Last Updated : 25 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one.

Defining a function in Kotlin:

Visibility modifier fun functionName (argument name: type name, ...): return type{
  .....
  // function body
  .....
  return value
 }

Normally, It is the proper way for defining a function in Kotlin.

Example:

private fun gfg1( a : Int, b :Int ): Int {
  var c : Int 
  c = a + b
  return c
}

Now we will look at the variation of this function.

Visibility Modifier

In Kotlin, we while defining a function it is optional to specify the Visibility modifier. If it is not mentioned while defining, by default it is considered public.

Example:

fun gfg2( a : Int, b :Int ): Int {
  var c : Int 
  c = a + b
  return c
}

Both the gfg1( ) and gfg2( ) are doing the same job, but gfg1 is a private function and gfg2 is a public function as we haven’t mentioned its Visibility modifier.

Single Expression Function

In Kotlin if the function has only one expression we can omit the curly braces. 

Example:

fun gfg3( a: Int , b :Int ) : Int  = a + b

Instead of curly braces, we using the’ = ‘ sign for the function body. We can also omit the return type in the Single expression function.

fun gfg4( a: Int , b :Int ) = a + b

gfg4( ) and gfg3( ) is same.

Return Type

In Kotlin, while defining the function we need to declare the type of data that is returning in the function. If we are returning nothing then we have the option to specify ‘unit‘ or if we do not specify anything, Kotlin will assume it as a function is returning nothing.

Example:

// declaring the return type as 
// unit as it isn't returning anything.
fun gfg5( a : Int): Unit {
  print(a)
}
// Here we have mention the return type,
// kotlin can infer the return type
fun gfg6( a : Int){
  print(a)
}

both gfg5 ( ) and gfg6 ( ) is same.

Argument

When we have lots of arguments in a function, it is difficult to remember the position of each of them. So, here we can use Name Arguments, Here we need to specify the name along with the values to the function. We can change the sequence of the values, the value will assign to an argument that will have the same name as the value have.

Example:

fun main( ){
    val res1 = gfg7( arg1 = 2, arg2 = 3) //using name argument 
    val res2 = gfg7( arg2 = 3, arg1 = 2 )  // sequence doesn't matter here.
    
}

fun gfg7( arg1 : Int, arg2 :Int ): Int {
  return arg1 + arg2
}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads