Functions in kotlin
In this blog, we are going to learn about functions in kotlin it is the most beautiful thing in kotlin.
In this, we will learn about the Extention function and also we will cover some basic stuff about the functions in kotlin.
Default Arguments :
There is a major difference between java functions and kotlin functions. We can not provide the default values of any arguments of functions in java if have a function that takes two arguments then we have to provide both of arguments to call that function but in the case of kotlin we have the facility to provide the default value.
Function parameters can have default values, which are used when you skip the corresponding argument. This reduces the number of overloads:
A default value is defined using =
after the type.
1 2 3 4 |
fun myFunction( p1: String, p2: Int = 0, ) { /*...*/ } |
Named arguments :
There is also a cool thing in kotlin functions. We can assign the value of an argument by just calling its name in the argument and assigning its value. The benefit of this approach is we don’t have to remember the sequence of that particular argument we just have to name that parameter and assign it value. It will automatically refer the value to the named argument. Below is an example of how we can use the named argument.
1 |
myFunction(p1 = "My first parameter value",p2 = 5) |
Extension functions :
Kotlin provides the ability to add and modify some new functionality in classes no matter it is a third-party class or a predefined class.
like we have a list and we want to add a new function in it that will return us the sum of the list that list have contained Integer values in it.
1 |
fun <class_name>.<method_name>() |
1 2 3 4 5 6 7 |
fun List<Int>.getSumOfList() : Int{ var sum : Int = 0 for (value in this){ sum += value } return sum } |
1 2 |
val myList : List<Int> = listOf(5,4,3,6,2) val sum = myList.getSumOfList() |
We will get 20 as the sum of myList.
Hope this blog will help you to understand the Extension functions and the basic concepts of kotlin functions.
Reference: https://kotlinlang.org/docs/functions.html#tail-recursive-functions