Types of Functions in Kotlin
inline,infix,operator
Introduction
A Function is a block of code that performs a specific task. It can be called from anywhere in a program. Kotlin functions are declared using the keyword fun.
fun double(x: Int): Int {
return 2 * x
}
Method are functions used to perform certain action.
Calling a function
val result = double(2)
print(result)
output
4
What is a function parameter? this is a variable defined during function declaration or definition. It’s data passed into a function, it is specified after the function name inside the parentheses. It is defined using pascal notation name:type.
Parameters are separated by commas.
fun powerOf(number: Int, exponent: Int): Int { /*...*/ }
Functional parameters can have default values. It is set by appending = to the type.
fun calc(
age: Int = 0,
len: Int = b.size,
) { /*...*/ }
Note: Overriding methods always use the base method’s default parameter. When ovveriding a method that has default parameter values, the default parameter values must be ommitted from the signature.
open class A {
open fun foo(i: Int = 10) { /*...*/ }
}
class B : A() {
override fun foo(i: Int) { /*...*/ } // No default value is allowed.
}
The open
keyword with the class means the class is open for the extension meaning that we can create a subclass of that open
class.
Return Values
To return a value from a function we used the keyword return and specify the return type after the functionL parenthesis.
fun myFunction(x: Int): Int {
return (x + 5)
}
fun main() {
var result = myFunction(3)
println(result)
}
You can use the = operator instead of return without specifying a type
fun myFunction(x: Int, y: Int) = x + y
fun main() {
var result = myFunction(3, 5)
println(result)
}
Inline Function
It instructs the compiler to insert the complete body of the function wherever that function gets used in the code.
Adv: Function overhead does not occur.
When to use:
- When the function code is very small
When not to use inline
- when the function code is large and called from so many places. It will be a bad idea since the code will be repeated again and again.
fun guide(){
print("guide start")
teach()
print("guide end")
}
inline fun teach(){
print("teach")
}
Infix Function
This function is called without any dot or parenthesis .
What makes an infix function
- Member function
- Has single parameter
- Is marked with infix keyword
Example
Or method
Operator Function
This is a function which is declared with a special keyword operator and are not different from regular functions when called via function calls.
It allows instance of a class to be called as if they were functions.
The invoke function is invoked when you use the parenthesis () syntax as the object of the class . Reference