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
- {
- //body statements. return
- <value>;
- }
Printing a message using function
- fun main(args: Array < String > )
- {
- println("Message=" + welcomeMessage())
- }
- fun welcomeMessage(): String {
- var msg: String = "Hello Android"
- return msg
- }
- // output: Message=Hello Android
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
- }
- //output: area of square=25
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) { //body statements}
- 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.
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)
- {
- // body statements…………………
- }
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")
- }
- //output: 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
- } //lambda function to calculate area
- fun main(args: Array < String > ) {
- println("Area of Rectangle=" + area(5.5, 5.5))
- }
- //output: Area of Rectangle=30.25
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.

Join the conversation! Your thoughts help the community grow.