C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Kotlin

Functions in Kotlin programming language

Functions are set of instructions that take some input and generate some output. The function is used to perform some specific task.They are useful when we have to repeat some piece of code many times. In this article we will learn, how to define functions and use them in Kotlin?
Submitted by Aman Gautam, on November 27, 2017

Functions are set of instructions that take some input and generate some output. The function is used to perform some specific task.They are useful when we have to repeat some piece of code many times. Every Kotlin program contains a main Function.

In Kotlin we define a function by using fun keyword, then followed by function name with parameter names. Parameters in Kotlin are defines using Pascal notation i.e. name : Type. Multiple parameters are separated by commas. After that, we specify the return type of the function.

fun add(a:Int,b:Int):Int{
	return a+b;
}

In this function, we have defined a function add which takes two Integer type parameter a and b and returns the addition (a+b) of Integer type.

Then we can call the function as follows,

var result = add(10, 20)

1) Single expression functions

When a function contains/returns only a single expression then the curly braces can be removed and single expression can be specified after = sign.

fun substract(a:Int, b:Int) = a-b 

2) Default Argument

We can also define function with default parameter.Default values are defined using the = sign after type along with the default value.

fun def Add(a:Int=10,b: Int):Int{
	return a+b;
}

Calling function always treats arguments with sequence as they appear in function definition so if we write like,

var result = def Add(10))

will be treated as def Add(a=10) and will produce error. So we have to provide named arguments in such cases.

var result = def Add(b=10))

3) Unit Returning function

If function does not return any value then its return type is Unit.

fun name(name:String):Unit{
	print(name)
	// return Unit is optional
}

This function does not need to return 'Unit' explicitly. Returning 'Unit' is optional.

The return type 'Unit' can also be Omitted from function definition. So the simplest form looks like,

fun name(name:String){
	print(name)
}

Program

package Basic

fun add(a:Int,b:Int):Int{
    return a+b;
}

fun substract(a:Int,b:Int)=a-b

fun defAdd(a:Int=10,b: Int):Int{
    return a+b;
}

fun name(name:String){
    print(name)
}

fun main(arg:Array<String>){
    var result=add(10,20)
    println(result)
    result = sub(20,10)
    println(result)
    result=defAdd(b=10)
    println(result)
    name("Aman")
}

Output

30
10
20
Aman








COMMENTS