Functions alias methods, take input, executes code statement blocks, returns output to the caller
when multiple code statements want to execute multiple times in different places, It is best to copy the code into functions.
It allows for code reusability and clean separation of modularity.
Function declaration contains the following components.
- function definition:
Contains
func
keyword, followed by the function name, arguments, and their types - Function return type: Contains return type of a value
- Function Body: Contains the body of a function enclosed in
{}
- Function Caller: after the Function is declared, executed using the name of the function with optional arguments and return type.
How to Declare and Call Function in Kotlin
The function contains the following syntax
fun functionname(argument: datatype): DataType{
//function body contains code block;
return value;
}
fun
is a keyword- functionname: Name of the function.
- Datatype: Function returns the value of Kotlin primitive or custom type.
- arguments: datatype: Contains multiple pairs of options arguments defined with type and arguments
- code-block: is a Kotlin code that executes in sequential order
- return value: the value returned from the function.
- the function body is enclosed in
{}
After the function is declared, The function is called with the below syntax. Function Invocation syntax::
functionname(arguments);
- functionname: calling this, executes the function
- arguments: parameters to the function.
Here is a simple function definition.
fun main() {
print(multifly(11, 3));
print(multifly(4, 3));
}
fun multifly(int first, int second):int {
var output = first * second;
return output;
}
Output:
33
12
Kotlin Function types
Functions are categorized into multiple types based on return type and arguments.
- Functions without arguments and return type:
This example contains a function with no arguments
and a return type
fun main() {
printMsg();
}
func printMsg() {
print("Welcome John");
}
- Functions without arguments and return type:
This example shows a function without arguments and returns a type
fun main() {
print(getMsg());
}
// function
fun getMsg() : String{
return "Welcome John";
}
The above simple function is rewritten using simplified shorthand syntax. The return type is skipped and the returned value is inferred to a datatype.
fun getMsg() = "Welcome John"
- Functions with arguments and without return type: This example shows a method with arguments and without a return type.
fun main() {
printMsg("john");
}
fun printMsg(name: String) {
print("Welcome $name");
}
- Functions with arguments and return type: This shows a declaration with arguments, and datatypes, and returns a type of a value
fun main() {
print(substraction(12, 2));
print(substraction(40, 20));
}
fun substraction(int one, int two): int {
var result = one - two;
return result;
}
Inline Functions in Kotlin
Kotlin supports functional programming using high-order functions,
Inline functions allow you to support high-order functions.
These are defined using the inline
keyword
Inline functions replaced declaration code at runtime
inline fun getMessage(name: String) = "$name, Welcome"
Here is an example
inline fun sayMyName(name: String) = print("Your name is $name");
fun main() {
val name = "John"
sayMyName(name);
}
After the above code is decompiled, the Code looks like as given below
inline fun sayMyName(name: String) = print("Your name is $name");
fun main() {
val name = "John"
print("Your name is $name")}
Inline functions help code to execute faster. The only disadvantage, these are not accessing the scopes of the variables where they are called.
Kotlin Lambda Functions
Lambda functions allow writing functions without a name. Also called anonymous functions.
Letβs define lambda expressions
val variablename : Type = { arguments -> body }
Notes:
- Lambda functions do not have a name
- Argument type can be skipped if arguments contain a single
- The last statement is a return value, can skip the
return
keyword - arguments and body are separated by
->
Here is an example
val add: (Int, Int) -> Int = { a: Int, b: Int -> a + b }
fun main() {
val name = add(10,20);
print(result);
How to pass variable arguments to functions in Kotlin
As of now, We have seen functions with a fixed length of arguments defined in functions.
Kotlin allows to passing of dynamic length of arguments using var arg
syntax.
vararg
pass multiple arguments as an array. Inside a function body, Iterates using array operations to access the values.
fun main (args: Array<String>) {
myfunctions ("one", "two", "three", "four", "five", "six")
}
fun myfunctions (first: String, vararg array: String) {
print(first)
for (item_ in array) {
print(item_)
}
}
Output:
onetwothreefourfivesix
Kotlin Functions Advantages
The function has advantages in Kotlin.
- Code declared once and used and executed in multiple places, allows reusability
- Code separation into feature and logic wise and enhances code
- Unit testing is very easy as you need to test functions only
- Development and productivity is improved
- Helps functions to debug and fix issues
Kotlin Functional optional arguments
Functional arguments can be options, which means the caller is not required to send arguments. In there are two types of optional argument types
- Positional Optional Arguments
- Optional Named parameters
- Optional Arguments with the default value
Kotlin Positional Optional Arguments
First, Letβs see positional argument syntax
The below function takes a string and an integer, First position is a string, second position is an integer.
if the first parameter is an integer, It throws an error.
Here is an example
fun main() {
justdoit("john", 10000)
}
fun justdoit(name: String, salary: Int) {
println("$name, $salary.") //π john,10000
}
Kotlin default values for an argument in a function
Optional arguments are passed with default values in the function declaration if their value is not passed.
Syntax:
void functionname(argument: datatype = "default value", ) {
// statements
}
Caller function syntax contains arguments that can contain a value or no value.
functionname(argument,arguments:values)
fun main() {
// supply both arguments
printEmployee("john", 10000);//π john,10000
//second argument is default
printEmployee("frank");
both arguments are default
printEmployee();
}
fun printEmployee(name: String= "default", salary: Int=1000) {
println("$name, $salary.")
}
Output:
john, 10000.
frank, 1000.
default, 1000.
Kotlin Named arguments examples
Functions Named arguments allow you to define a variable and map the values to it
Named arguments are declared with argument=value
.
void functionname(argument: datatype="default") {
// statements
}
functionname(argument="newvalue");
argument
contains a type and default value, multiple arguments are separated by a comma.
Caller function syntax contains
the function called with passing normal arguments with value and named arguments with argument= value
syntax
if the caller is not passed with optional arguments, the value null is passed.
functionname(argument,arguments:values)
Here is an example
fun main() {
printNumbers(10, number2= 20);
}
fun printNumbers(number1:Int=0 ,number2: Int = 1, number3: Int=2) {
print(number1); // π 10
print(number2);// π 20
print(number3); // π 2
}