Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Function

Function is a mini program with a name. It takes some (or no) input, does some operations and gives an (or no) output.

Basics

 fun main() {
    print("Hello World!")
}
 

In this program, main & println are two different functions.

Using a function involves two basic steps - Definition & Invocation.

Definition

Before a function / mini-program is used, it must be defined somewhere. Defining a function involves

  • giving it a name
  • defining what it’s inputs (or arguments) (no / single / multiple) will be
  • defining what it’s output (no / single) will be
  • the program / code that instructs the computer to do what the function is intended to do

Syntax for defining a function is :

 fun functionName(/* Inputs */): /* Output */ {
    /* Code */
}
 

The function code is enclosed in curly braces {}.

Example - a function that computes and returns square of the input number can be defined as :

 fun square(x: Int) {
		return x*x
}
 

We use the return keyword to return the output.

Invocation

Invocation (or calling a function) means execution of the function, in which its code is read and executed line by line. Syntax for calling a function :

 functionName(/* Inputs */)
 

For example, we can call the println() function like this :

 fun main() {
		println("Hello World!") // Prints "Hello World!"
}
 

The function that returns square of a number can be invoked as :

 fun main() {
		println(square(5)) // Prints "25"
}
 

main() function

Below we have defined the main function which takes no input & returns no output :

 fun main() {
    print("Hello World!")
}
 

main function is the entry point of the program. It’s name should be main only. We can not run a project without a main funcntion. Whatever code that we need to execute, has to be written inside this main function.

You might wonder we have only defined the main function, but haven’t called it. We don’t have to call the main function, defining it is enough. The IDE automatically calls it when the project is run.

One Line functions

If the function body (code) consists of just one statement, then we can omit the curly braces {} and define a One line function.

 fun name(/* inputs */) = /* output */
 

Examples :

 fun square(x: Int) = x * x
fun double(x: Int) = 2 * x
fun perimeterOfRectangle(l: Int, b: Int) = 2 * (l + b)
fun decorPrint(text: String) = println("*-*-> $text <-*-*")

fun main() {
		println(square(3)) // Prints "9"
		println(double(49)) // Prints "98"
		println(perimeterOfRectangle(3, 2)) // Prints "10"
		decorPrint("HIMALAYAS") // Prints "*-*-> HIMALAYAS <-*-*"
}
 

Default value and Named arguments

We can define default values for function arguments (inputs). Then it becomes optional to pass value for such arguments.

 fun name(arg: type = defaultValue, ...) { /*...*/ }
 

Lets define a function to compute the Simple Interest based on the given inputs : p (Principal amount), r (rate of interest) & t (time period in years) :

 fun simpleInterest(
		p: Int, 
		r: Int, 
		t: Int
) = p * r * t / 100f
 

Now we need to define default value for rate & time as 8% and 1 year respectively. We can easily do so using default argument values :

 fun simpleInterest(
		p: Int, 
		r: Int = 8, 
		t: Int = 1
) = p * r * t / 100f
 

Note that we can not remove an argument’s type even though we pass a default value for it. Type inference does not work here. So, following code won’t work :

 fun simpleInterest(
		p: Int, 
		r = 8, 
		t = 1
) = p * r * t / 100f
 

This function can then be invoked in several ways :

 fun main() {
		// One argument i.e. p is passed
		println(simpleInterest(1000)) // (p=1000, r=8, t=1) Prints "80"

		// Two arguments i.e. p & r are passed
		println(simpleInterest(1000, 10)) // (p=1000, r=10, t=1) Prints "100"

		// All arguments i.e. p, r & t are passed
		println(simpleInterest(1000, 10, 2)) // (p=1000, r=10, t=2) Prints "200"
}

fun simpleInterest(
		p: Int, 
		r: Int = 8, 
		t: Int = 1
) = p * r * t / 100f
 

Are there more ways to invoke this function? Of course, there is one more way i.e. passing two arguments - p & t and let r be of the default value. We already saw that when 2 arguments are passed, p & r receive the values and not p & t. Then, how do we do so?

This is where Named arguments come into picture. When we need to pass function arguments in an order that is different from the function argument list order, we use Named arguments.

 funName(arg1 = val1, arg2 = val2, ...)
 

For example, here the function argument list order is p, r, t. But we want to pass p, t only whereas r has to take default value. The argument order is changed here because we want to skip r. Using named arguments, we can do this as :

 // Two arguments i.e. p & t are passed
println(simpleInterest(p = 1000, t = 2)) // (p=1000, r=8, t=2) Prints "160"
 

When we do not use named arguments, values for arguments are passed in the argument list order. For instance, following invocation implicitly assigns values to arguments in the p, r, t order :

 simpleInterest(1000, 10) // (p=1000, r=10, t=1)
 

When passing p & t only, the order of p is unchanged but that of t is changed. So, we can omit the argument name from p and simply rewrite as :

 // Two arguments i.e. p & t are passed
println(simpleInterest(1000, t = 2)) // (p=1000, r=8, t=2) Prints "160"