Updated March 14, 2023
Introduction to Kotlin Functions
Just like most other programming languages, you can create and utilize Functions in Kotlin. You can think of Functions as a basic building block for any program. These are used to streamline the code and to save time. A function in a program is a group of related statements and instructions that do one specific task. Once a function is made, we can call it anytime we want in the program; this removes the tedium of writing the same statement in a program multiple times. Functions are a great way to break any Kotlin code into modular chunks. It helps reduce the size of the program, but it will also make the code more reusable.
In Kotlin, we can declare a function by using the keyword “fun”. As you can expect, we can pass arguments into it, and we need to set a return type with a function in Kotlin.
Functions in Kotlin
The general syntax to declare a function in Kotlin is as following:
fun nameOfFunction(param1: Type1, param2: Type2,..., paramN: TypeN): Type {
// Body of the method here
}
In other words:
fun nameOfFunction (arguments_here): return_type {
// function body
}
As an example, the following is a function that we can use to calculate the average of two numbers:
Code:
fun avg(a: Double, b: Double): Double {
return (a + b)/2
}
Calling a function is as simple as any other language:
avg(10.0, 20.0)
As you can expect, the result of running the code is 15.
Types of Functions in Kotlin
Depending on where the function originated from, we can divide it into two types.
- Kotlin Standard Library Functions
- User-Defined Kotlin Functions
1. Standard Library Functions
To save user’s time for common tasks, Kotlin comes with some standard library functions which do not need to be defined by users to use in the program. For example. Print() is a common function that is used to show a message to the monitor. Similarly, sqrt() is a standard library function that is used to calculate the square root of the provided number.
Code:
fun main(args: Array<String>){
var number = 100
var result = Math.sqrt(number.toDouble())
print("The root of $number = $result")
}
Output:
Here sqrt() does not have to be declared before its use.
Following are some of the common Standard Library Functions in Kotlin:
- print(): Prints the message to the output.
- printIn(): prints the message and then moves the cursor to the next line.
- dec(): Decreases the value of a given number by one.
- plus(): This is used to add two values.
- minus(): This is used to subtract two one values from another.
- div(): Divide one value from another.
- plusAssing(): Adds one number with another and then assigns the summation result to the place of the first number.
- sqrt(): As we have seen already, it is used to calculate the square root of a given number.
2. User-Defined Functions
While Standard Library has some common functions to do some basic and repetitive tasks, eventually, you will find the need to declare your own functions. functions that are declared and defined by users are called User-defined Functions. We have already seen the syntax for declaring a Kotlin Function here; let’s look at another example that adds two numbers.
Code:
fun main(args: Array<String>){
sum()
print("Addition Done")
}
fun sum(){
var num1 = 55
var num2 = 30
println("Answer of addition = "+(num1+num2))
}
Output:
Depending on how they are made, the following are some other types of functions:
3. Member Functions
Member functions, as you can guess, are defined inside of an object, interface or class. These are used to take modularization into another level:
Code:
class draw_Circle {
fun areaCalculate(radius: Double): Double {
require( radius > 0, { " Please pick radius more than zero " } )
return Math.PI * Math.pow(radius, 2.0)
}
}
The above has a member function areaCalculate(), and it takes a radius to calculate the area of the circle.
4. Inline Kotlin Functions
When a function is declared inside the main() function, we call it an Inline Function. These are used some time to save time. Following is an example of an inline function in Kotlin, it takes two integer values int1 and int2 and then adds them.
Code:
fun main(args : Array < String > ) {
val sum = {int1: Int, int2: Int -> int1+ int2 }
println (" 5 + 6 = ${sum(5,6)} ")
}
Output:
5. Local Functions
We can declare functions inside of functions in Kotlin; these are known as Local Functions.
Code:
fun outerFunction(param: String) {
fun localFunction(innerParam: String) { // This is the local function
println(innerParam)
println(param)
}
}
6. Lambda Function
A Lambda is a high-level function in Kotlin. In a nutshell, it is an anonymous function. We can define our own Lambda in Kotlin and pass that to a function.
Code:
fun main(args: Array<String>) {
val myfunctionlambda :(String)->Unit = {s:String->print(s)}
val v:String = "educba.com"
myfunctionlambda (v)
}
As you can see above, we have made our own lambda known as “myfunctionlambda”, and then, we have passed a variable which is a string in type, and its value is “educba.com”
After being executed, the code above will show the following result:
Output:
Conclusion
Now that you are familiar with the above, their uses, and their types, you can declare and use them in your programs. Functions are not only useful in keeping your code less messy; in the case of large programs, you will also see that these are some of the core pillars of the programming that make the development much easier. Writing your own functions to reuse in your code and using standard library functions will help you greatly in your programming career.
Recommended Articles
This has been a guide to Kotlin Functions. Here we discuss the introduction and different types of functions in Kotlin along with examples and outputs. You may also have a look at the following articles to learn more –