Function
Function is a set of code which may take some parameters, perform certain operations on them, and then may return a value.
Kotlin uses "fun" keyword to declare a function, and you can use traditional ways, like C, C++, and Java, to call them.
General Syntax
- <Access specifire> fun
- <Function name>(parametors) : returntype
- {
-
- <value>;
- }
Example
Printing a message using function
- fun main(args: Array < String > )
- {
- println("Message=" + welcomeMessage())
- }
- fun welcomeMessage(): String {
- var msg: String = "Hello Android"
- return msg
- }
-
Passing Parameters
Function parameters are defined as name: type. Parameters are separated using comma. Each parameter must be explicitly typed.
- fun main(args: Array < String > )
- {
- println("area of square=" + area(5))
- }
- fun area(x: Int): Int {
- return x * x
- }
-
Default Arguments
You can use the default value of parameter when the corresponding parameter is omitted.
- fun read(off: Int = 0, length: Int = b.size) {
- Default values are defined using the =after type along with the value.
- Overriding methods always use the same default parameter values as the base method.
Named Argument
You can name a list of parameters for making it readable and for convenience.
- fun sample(pwd: String, wordseparator: Char = ’_’, uppercase: Boolean = true, lowercse: Boolean = true, number: Boolean = true, specialchar: Boolean = true)
- {
-
- }
Now, you can call this function like this –
sample(pwd)
or sample(pwd,true,true,true)
Unit Returning Type
It is optional return type. Suppose, you do not want to return any value/data from Function. You can use Unit type.
Example
- fun main(args: Array < String > ) {
- showMessage();
- }
- fun showMessage(): Unit {
- println("Hello Android")
- }
-
Lambda Function
Syntax
- val functionName = {
- param_var: Type - > operation
- }
- or
- val functionname: (param_Type) - > return_Type = {
- operation on param here
- }
- now you can use it as traditional
- function call i.e.–
- function_name(param)
Example
Create a lambda function to calculate the area of a rectangle.
- val area =
- {
- width: Double,
- height: Double - > width * height
- }
- fun main(args: Array < String > ) {
- println("Area of Rectangle=" + area(5.5, 5.5))
- }
-
Inline Function
When you use the inline keyword with function, it copies the body statement of the inline function at its invoking code which reduces the control jumping from calling statement to a definition of the function.
Example
Write a program to illustrate inline function.
- inline fun printMessage(message: () - > Unit) {
- println("Line before calling lambda function")
- message()
- println("Line after calling lambda function")
- }
- fun main(args: Array < String > ) {
- printMessage {
- println("Calling exact function")
- }
- }
-
-
-
-
-
-
-
-
-
-
-
Use ctrl+shift+A to get the search dialog and search here for Kotlin bytecode. You can see the bytecode so now, decompile this bytecode which will be visible in Java.
- public final class Example_inline_lambdaKt {
- public static final void printMessage(@NotNull Function0 message) {
- Intrinsics.checkParameterIsNotNull(message, "message");
- String var2 = "Line before calling lambda function";
- System.out.println(var2);
- message.invoke();
- var2 = "Line after calling lambda function";
- System.out.println(var2);
- }
-
- public static final void main(@NotNull String[] args) {
- Intrinsics.checkParameterIsNotNull(args, "args");
- String var1 = "Line before calling lambda function";
- System.out.println(var1);
- String var2 = "Calling exact function";
- System.out.println(var2);
- var1 = "Line after calling lambda function";
- System.out.println(var1);
- }
- }
tailrec function [Recursive Function]
Recursive functions are those functions which call themselves several times within their body .You can use ’tailrec’ keyword before fun keyword in function definition. This keyword prevents the program from stack overflow. Let us understand working of this keyword with an example-
Example
Write a program to find nth number of Fibonacci series.
- import java.math.BigInteger
- fun main(args: Array < String > ) {
- println("factorial =" + getfabinockyNum(10000, BigInteger("1"), BigInteger("1")))
- }
- tailrec fun getfabinockyNum(n: Int, a: BigInteger, b: BigInteger): BigInteger {
- if (n == 0) {
- return b
- } else {
- return getfabinockyNum(n - 1, a + b, a)
- }
- }
- Without using ‘tailrec’ keyword, this program will return ‘StackOverflow ’ exception.
High Order Functions
When a function has a function as a parameter, it is called high order function .To understand better with user defined function, see the example of Inline Function.
- fun main(args: Array < String > )
- {
- var data = mutableListOf < Int > (1, 2, 3, 4, 5)
- data.forEach {
- println(it)
- }
- }
-
- 1
- 2
- 3
- 4
- 5
Explanation
In this example, ‘forEach()’ has a method println() as a parameter. It takes a single element of the list one by one and put it in variable ‘it’ which will be printed using println() method. This is the abbreviated code of data.forEach{println(it)}.
- For(x in data)
- {
- println(x)
- }