Design Converter
Education
Software Development Executive - II
Last updated on Sep 5, 2024
Last updated on May 17, 2024
Welcome to my detailed guide on understanding Kotlin functions.
A function in Kotlin, much like other languages, is defined as a block of code designed to perform a specific task. Functions are a fundamental aspect of a program as they help in structuring the code and making it reusable. Consequently, if you need to execute the same code multiple times, you don’t need to rewrite it.
You can create your own functions (user-defined functions) once, and call the function wherever required. Kotlin also includes standard library functions like arrayOf(), sum(), println(), and rem(), which are built-in functions readily available for use, enhancing the language's efficiency and ease of use.
In Kotlin language, functions are defined using the fun keyword. Kotlin offers ease and flexibility when it comes to writing functions. Kotlin functions can either be Member Function (a function within a class) or Standard Library Function (functions built into the Kotlin Standard Library).
Below is an instance of a function definition in Kotlin:
1fun functionName(parameter: dataType, ..): returnType { 2 // function body 3}
In the above code, fun is a keyword. The functionName represents the name of the function, dataType indicates the data type of parameters (like Int, String), and returnType signifies the data type of the value the function returns. The function may or may not return a value.
A function in Kotlin is written by using the fun keyword – as seen in the example in the previous section. The standard format of writing a function is fun, followed by the name of the function. Let’s consider the general fun main() function that is often the entry point of any Kotlin program:
1fun main(args: Array<String>) { 2 println("Welcome to Kotlin!") 3}
In the above example, the main is the name of the function. args: Array<String>
is the parameter passed in the function, while Array<String>
is the data type of the parameter. The actual function body, which is enclosed within the curly braces {…}
, contains the block of code to execute and is also known as a block body.
Let’s now look at creating our functions. To declare a function in Kotlin, we use the fun keyword, followed by a unique function name, a list of zero or more comma-separated parameters, an optional return type, and a function body. If the function does not return any value, its return type needs to be specified as Unit. It can be omitted as the compiler understands it implicitly.
Now let’s explore the function parameters of Kotlin functions, which are crucial for executing specific tasks.
1fun addTwoNumbers(num1: Int, num2: Int): Int { 2 var sum = num1 + num2 3 return sum 4}
In the user-defined function above, num1 and num2 are two parameters of type Int, and Int after colon : is the return type. It specifies that this function will return an integer value. The return sum statement specifies the value to return.
Function parameters are the input values defined in the function definition. A function can have multiple parameters, allowing for extensive flexibility in passing information. They hold different values every time we call a function with new argument values. Here is an example:
1fun greet(name: String, msg: String) { 2 println("Hello $name, $msg") 3}
In this example, name and string are the parameters of the greet function. The function expects two arguments of string type. You can provide the values for these parameters at the time of the function call:
1fun main() { 2 greet("Kotlin Learner", "Keep Coding!") 3}
In the above Kotlin program, Kotlin Learner and Keep Coding! are the arguments. As a rule, the actual arguments should be of the same order and the same data type as their corresponding parameters. Additionally, function parameters can have default values, which are used when corresponding arguments are omitted, simplifying function calls and enhancing code readability.
In a Kotlin function, the function body is the part where all the magic happens. As you saw in the examples of the previous sections, the function body is defined inside the curly braces {…}
. When a function call is made, the control of the program goes from the function call to the function body, where it starts executing the logic defined inside the function.
There are two types of Kotlin functions, based on what they return. Functions that return a value, and functions that do not return any value (Unit type).
1fun giveMeFive(): Int { // Function Definition 2 return 5 3} 4 5fun main() { // Function Call 6 val x: Int = giveMeFive() 7 println(x) 8}
In the above example, the function giveMeFive is declared with a return statement that returns an Int type. The return keyword is used to return the value. The fun main(), where we print the return value 5.
Note: The return type of a function is mentioned after the parameter list followed by a colon.
Not all functions in Kotlin return values; some functions perform a specific task without returning anything. Where such functions lack a return statement, they return a Unit. The Unit keyword denotes 'no value'. It's comparable to void in Java. You can omit writing it, as the compiler understands it implicitly.
In Kotlin, every function parameter has its unique name and specifies the type of the parameter. When you define a function, you can include parameters like so:
1fun multiplyTwoNumbers(num1: Int, num2: Int): Int { 2 return num1 * num2 3}
In the above code, num1 and num2 are parameters and each of them is of data type Int. When calling this function, we will need to provide two arguments, both of the datatype Int.
1fun main() { 2 var result = multiplyTwoNumbers(3, 4) 3 println(result) // prints 12 4}
In this example, 3 and 4 are the arguments passed in the function call that correspond to the parameters num1 and num2 respectively.
Now that we've established the basics of Kotlin functions, let's take a look at some of the powerful features offered by Kotlin.
Kotlin provides the advantage of conciseness over many traditional languages. This means we can write less code to perform complex operations. For instance, functions in Kotlin can be declared in a single expression:
1fun sum(a: Int, b: Int): Int = a + b
In the above function, the result is implicitly defined by the expression a + b. There's no need for a return keyword or curly braces.
Kotlin also supports variable length arguments or varargs . Using vararg keyword in the function's parameter, we can pass any number of arguments of the same data type. For example:
1fun printAll(vararg numbers: Int){ 2 for (number in numbers) println(number) 3} 4 5fun main(){ 6 printAll(1,2,3,4,5) // You can pass any number of arguments 7}
Higher-order functions and lambda functions are also an important part of Kotlin. A higher-order function can take functions as parameters and return a function.
1fun multiplyBy(factor: Int): (Int) -> Int { 2 return { number -> number * factor } 3} 4 5fun main() { 6 val multiplyBy2 = multiplyBy(2) 7 println(multiplyBy2(4)) // prints 8 8}
In the code above, the multiplyBy() function returns a function that multiples its argument by the specified factor.
One very useful feature provided by Kotlin is named parameters. At the function call site, you can specify parameter names alongside their values for more explicit and self-documenting code. Named parameters to enhance code readability and minimize errors caused by parameter order mix-ups.
1fun friendInfo(name: String, age: Int, city: String) { 2 println("$name is $age years old and from $city") 3} 4 5fun main() { 6 friendInfo(age = 30, city = "New York", name = "John") 7 // prints "John is 30 years old and from New York" 8}
In the main function call, we've used named arguments where the order of arguments doesn't correspond to the order of parameters in the function definition. Despite this, the program works fine, demonstrating the advantage of using named parameters.
To become fluent in Kotlin, it's important to have an understanding of Kotlin's inline and extension functions.
Kotlin's inline functions are powerful tools that optimize your code by reducing call overhead. When the code is executed and an inline function is called, instead of executing the standard function call protocol, the compiler copies the parameters and the function itself to the call site. This can increase performance for functions like higher-order functions that take lambda as parameters.
1inline fun modifyString(str: String, operation: (String) -> String): String { 2 return operation(str) 3} 4 5fun main() { 6 val str = "Hello " 7 val str2 = modifyString(str) { it -> "$it World!" } 8 println(str2) // prints "Hello World!" 9}
In this example, modifyString is an inline function and takes two parameters. The second parameter is a function type.
Inline functions should be used judiciously considering they can increase code size. They are beneficial mostly for higher-order functions and lambda expressions. So next time, you come across performance issues, consider using inline functions.
Another beautiful concept is the extension function. Kotlin allows us to add more functions to a class without modifying its source code. These functions are called extension functions.
1fun String.add(s: String): String { 2 return this + s 3} 4 5fun main() { 6 val str = "Hello" 7 println(str.add(" World!")) // prints "Hello World!" 8}
In the code above, we create a new function add() for the String class.
Kotlin's inline functions, as mentioned earlier, help optimize code by replacing instances of these functions with their function body at compile time. Besides reducing the runtime overhead of function calls, especially higher-order functions, they allow some language features, like non-local returns and reified generics.
Here's an example of an inline function:
1inline fun printMe(num: Int, printer: (Int) -> Unit) { 2 printer(num) 3} 4 5fun main() { 6 printMe(10) { println(it) } // prints "10" 7}
In this Kotlin program, printMe is an inline function taking an integer and a function as parameters. The second parameter, a lambda expression in the function call, is the actual operation to be performed in the inline function.
In some scenarios, you may want to allow a function to be called with a variable number of arguments. This can be achieved in Kotlin using vararg.
The vararg modifier allows you to pass any number of arguments by separating them with a comma.
1fun printAll(vararg numbers: Int){ 2 for (number in numbers) println(number) 3} 4 5fun main(){ 6 printAll(1,2,3,4,5) // prints 1,2,3,4,5 each number on a new line 7}
In this function definition, numbers is a vararg of Int, allowing you to pass in any number of integer arguments when calling the function.
We’ve come a long way in exploring Kotlin functions starting from declaration and definition, understanding function parameters, and function body, and diving deep into features like Inline functions, higher-order functions, vararg parameters to name a few. The 'above program' sections were meticulously designed to guide you through the intricacies of Kotlin functions.
Each section in this blog was carefully curated to provide you with a wholesome understanding of how functions work in the Kotlin language. We also touched upon how functions play an essential part in simplifying code and making it readable with features like named parameters.
Remember, a function in Kotlin is made using the fun keyword, followed by the function name. The function body is where the code resides. A function can take parameters and optionally return a value.
In a nutshell, Kotlin functions enhance code’s reusability, manageability, and readability. As you continue your coding journey, keep experimenting and exploring with more complex functions in Kotlin. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.