Functions are main basic building blocks for any programing language. In this chapter we are going to read about how to create, call, argument functions in kotlin
Create a Function
fun add(a:int,b:int):Int
{
return a+b
}
Calling a function is simple. We just need to pass the required number of parameters in the function name
add(1,100)
Syntax of function declaration in kotlin
fun funName(varName:Type,....):Type{
//Body of the Method
}
Every function declaration has a function name, a list of comma-separated parameters, an optional return type, and a method body. The function parameters must be explicitly typed We can also define the functions in single expression
fun avg(a:Double,b:Double)=(a+b)/2
avg(1.2,1.8)
Output : 1.5
void type in Kotlin
Functions which don't return any type will have default return type, which is "Unit" In Kotlin return type Unit is similor to void in Java
fun printAverage(a: Double, b: Double): Unit {
println("Avg of ($a, $b) = ${(a + b)/2}")
}
is similar to
fun printAverage(a: Double, b: Double) {
println("Avg of ($a, $b) = ${(a + b)/2}")
}
Note :The Unit type declaration is completely optional
Default Argument Functions
Kotlin support default argumnets in function declaration. we can assign the default value for the variable, this value will be used when the corresponding argument doesn't pass from the called function.
fun displayIntro(message: String, name: String = "Kotlin") {
println("Hello $name, $message")
}
displayIntro("Welcome ","Android")
displayIntro("Welcome ")
Output : Hello Android Welcome
Output : Hello Kotlin Welcome
If function declaration has a default parameter preceding a non-default parameter, then the default value cannot be used while calling the function with position-based arguments.
fun displayIntro(message: String="Welcom", name: String ) {
println("Hello $name, $message")
}
displayIntro("Welcome to ") //error: no value passed for parameter name
Named Arguments
fun displayIntro(message: String="Welcom", name: String ) {
println("Hello $name, $message")
}
displayIntro(name="Kotlin")
We can also reorder the arguments if you’re specifying the names
fun displayIntro(message: String="Welcom", name: String ) {
println("Hello $name, $message")
}
displayIntro(name="Kotlin",message="Welcome to" )
The following function call is not allowed, it contains position-based arguments after named arguments
displayIntro(name="Kotlin" ,"Kotlin") // error: mixing named and positioned arguments is not allowedNumber of Arguments as array
fun sumOfNumbers(vararg numbers: Double): Double {
var sum: Double = 0.0
for(number in numbers) {
sum += number
}
return sum
}
sumOfNumbers(1.5,1.5)
sumOfNumbers(1.5,1.5,2)
sumOfNumbers(1.5,1.5,2.0,4.2,5.3)
If any function has varargs following with other arguments, then these function call with named arguments.
fun sumOfNumbers(vararg numbers: Double,avg:Int ): Double {
var sum: Double = 0.0
for(number in numbers) {
sum += number
}
return sum+avg
}
sumOfNumbers(1.5,1.5,avg=20) //23.0
Spread Operator
We can pass the arguments to a vararg function one-by-one. But if we want to pass the elements of the array to the vararg function, then you can use the spread operator
val a = doubleArrayOf(1.5, 1.5, 1.6)
sumOfNumbers(*a) // Result = 23.0
Function Scope
Functions can be categorized as Top Level Functions: These do not need a class to be enclosed in. Member Functions: These are defined inside a class or Object Local or Nested Functions: Functions that are defined in another function fall into this type. Kotlin has its own set of functions such as main(), println()
Top Level Function
Top level functions in kotlin are defined out side of the class. main() it self is Top level function. Package level functions is also defined as Top level functions
Member Functions
Member functions are defined inside the member of any classclass User(val firstName: String, val lastName: String) {
// Member function
fun getFullName(): String {
return firstName + " " + lastName
}
}
Here getFullName() is member function of class User Member functions are only called by class object
Local Functions
Kotlin support nested functions, a function defined inside other function is treat as Lolcal/Inner functions
fun areaOfTriangle(width:Double,height:Double):Double
{
if(width<0)
throw IllegalArgumentException();
if(height<=0)
throw IllegalArgumentException();
fun calculate(b:Double,h:Double):Double{
return b*h/2
}
return calculate(width,height);
}
areaOfTriangle(2.0,5.2)
Output : 5.2
//Here calculate() is local/ nested function
Lambda Functions
Lambda is a inline function, which is also know as Anonymous function. We will define lambda function in kotlin like below
{_var -> code_implementation}
Example
fun main(args: Array){
//lambda function
val add = {num1: Int, num2: Int -> num1 + num2}
println("1+2: ${add(1,2)}")
}