In this section, we will learn what the functions are and how to use them in Kotlin.
What is Function in Kotlin?
A function is a block of code with a name (label) on it.
We use functions when there are a set of instructions that we want to use in multiple places of a source code. Now instead of just copy and pasting those instructions in every place that is needed, we can simply write those instructions in a function (hence in just one place) and then use the name of that function in every place we might need the source code.
Kotlin is then smart enough to realize that we want to invoke the body of the target function when it sees the name of a function is invoked in places of the source code. So it will go to the place where the function’s body is written and runs the instructions of that function.
After running the instructions of the function, Kotlin will then come back and continue to run the tasks the comes after the statement that called the function.
Alright, enough with theory and now let’s get into the syntax of the functions and see how to practically create and use them.
Kotlin Function Syntax and Definition: Defining a Function in Kotlin
fun functionName (parameter1: data-type, parameter2:data-type, parameter_n:data-type):return-type { #instructions… }
Kotlin fun Keyword
In order to create a function, we first start with the keyword fun
.
Note that when you create a function, you need to use this keyword. But after creating the function, when want to call (invoke) that function, you don’t need to use this keyword anymore.
Function Identifier in Kotlin
The name of a function is known as the identifier of that function. The name of a function could be anything, but usually we use names that define what type of task that function does! For example, if the function runs multiplication operation, we might want to name it multiply
or something that reminds developers of the purpose of that function.
Note: the rules and conventions we define for variable’s name also apply to the name of functions.
Function Parameters in Kotlin
A function might be designed to run a set of tasks on a set of values! This means when calling the function, we might need to pass one or more inputs to the function as well if want that function to work properly.
Now there are a couple of questions to be answered here:
– How do we know whether a function needs a value?
– Let’s say a function takes x number of values when calling it; How to find these values in the body of a function, then?
– How can we access those values in the body of a function?
The answer to all of these questions is parameters!
Parameters are the local variables of a function, and we set them within the parentheses that come after the name of a function.
Note that they are constant variables (meaning it’s as if they are created using the val
keyword).
When a function needs one or more values, we set the same amount of parameters for that function to declare that the function should be called with values to work properly.
For example, let’s say a function needs two values of type String when it’s being called. Then this is how we set the two parameters for it:
fun functionName (parameter1:String, parameter2:String)
As you can see, the way we declare a function is just like the way we create a variable.
Note: for more than one parameter, we need to separate them using a comma.
Now, for this particular example, if the functionName
is called anywhere in a program, we need to pass two values to the function as well. Otherwise we will get an error.
After calling a function and passing values to it, the first value will be assigned to the parameter1
, the second one to the parameter2
and so on… until all the values (AKA arguments) are assigned to their relative parameters.
Function Return Value
A function is capable of returning a value as well! For example, let’s say you have a mathematical function which it takes multiple values, run a set of operations on those values and then finally it will return the result to the caller of the function.
Now, to make a function to return a value, we need to first set the data type of the value that a function returns as part of the signature of the function.
For example:
fun functionName(parameters…) :Int { }
Here, this function returns a value of type Int any time we call it. Note that the data type of function is set after the pair of parentheses of a function and they are prefixed with a colon.
Also, if the target function does not return a value, you can set the optional value Unit
as the return type of the function. This means the function does not return a value.
For example:
fun functionName() :Unit { }
Note: the use of Unit
data type is optional and if the target function does not return a value, you can simply leave the return data type off.
For example:
fun functionName(){ }
Example: Kotlin function with multiple parameters
fun main(){ } fun sayHello (name:String, lastName:String, age:Int ) { println("Hello ${name} ${lastName}, your age is ${age} ") }
Here we have two functions:
The famous main
function that we’ve been using throughout our examples in this tutorial and `sayHello`.
The main
function doesn’t have any parameter and so the caller of the main function (which is the JVM) won’t pass any argument to it when the main method gets called.
On the other hand, we have the sayHello
function with 3 parameters: name
, lastName
, and age
.
The data type of the first two parameters is String and the third parameter’s type is Int.
This means when the function is called in the program, we need to pass three values to it. The data type of the first two values should be of type String and the third value must be of type Int.
Alright, now that we’ve seen how to create a function in Kotlin, let’s see how to call the function.
Calling a Function in Kotlin: How to Call a Function in Kotlin?
This is the syntax on how we call a function in Kotlin:
functionName(value1, value2, value_n)
First, we start with the name of that function.
After the name of the function comes a pair of parentheses and within it we put the values that the function needs (if any).
For example, if the function has two parameters of type String and Integer, then we need to pass two values of type String an Integer respectively into the parentheses when the function is called in order to fill those parameters of the function.
Example: calling a function in Kotlin
fun main(){ sayHello("John","Doe", 50) } fun sayHello (name:String, lastName:String, age:Int ) { println("Hello ${name} ${lastName}, your age is ${age} ") }
Output:
Hello John Doe, your age is 50
As you can see, here, the sayHello function has three parameters. This means we need to pass three arguments to the function when it’s called.
After calling the function, your program will invoke the body of that function and:
– First, it passes the arguments of the function to the parameters as follows:
name = “John” lastName = “Doe” age = 50
– After that it will run the statements of the function which in this case there’s only one, and that is a call to the println function.
– After running the statement of this function, the program will terminate the sayHello function (because there’s no other statement to be run) and return back to where the function was called.
Now the program will continue to run any other statement left in the main function to run (which in this case, there is none).
That’s how we call and run a function.
What is Argument in Kotlin?
An argument is the value we pass to a function when that function is called. For example, in the program above, we’ve passed 3 arguments on the sayHello function.
Types of Arguments in Kotlin
When calling a function, there are two ways in which we can pass arguments to a function:
- Positional Arguments
- Keyword Arguments
Kotlin Positional Arguments
The positional arguments are the way we’ve been doing so far in the previous examples.
Basically, using the positional arguments, the first argument to the function will be assigned to the first parameter of that function, the second argument to the second parameter, the third argument to the third parameter, and so on.
Example: using position arguments in Kotlin
fun main(){ var res = multiply(10, 30) println(res) } fun multiply (val1:Int, val2:Int):Int { return val1 * val2 }
Output:
300
Here the name of the function is multiply
, it has two parameters of type Int which means we need to pass two integer numbers when calling the function. Also note that this function returns a value as well (we will talk about the return statement in the body of the multiply function in just a minute).
Now look at the body of the main function where we called the multiply
. Here we’ve used the positional arguments and send two values into the function.
So the first argument is passed to the val1
parameter and the second parameter val2
took the second argument of the function.
Also look at the position where we’ve called the multiply
function! It is on the right side of the assignment operator of the res
variable.
This means after calling the method, its result (Its return value) will be assigned to the res
variable.
That’s how when we called the println
function to get the value of the res variable, the value 300 appeared on the output.
Kotlin Keyword Arguments (Named arguments)
The second method of calling a function and passing arguments to it is by using the name of the parameters of that function!
You can think of it as calling a variable (the parameter in this case) and assigning a value to it. But everything happens within the parentheses of the target function.
Example: using keyword arguments in Kotlin
fun main(){ var res = multiply(val2 = 10, val1 = 30) println(res) } fun multiply (val1:Int, val2:Int):Int { return val1 * val2 }
Output:
300
Look at the way we’ve called the multiply function here! We basically used the name of the parameters of the multiply function and set a value for each one of them using the assignment operator.
Also, as you can see, the position of parameters at this call is changed! Basically, when using keyword argument, the order is no-longer matter! That’s why we could change the positions and no error occurred.
Kotlin return Statement
The return statement is used within the body of functions that should return a value!
In the next section (Kotlin return Statement) we’ll explain this statement in great details but in short, you call this keyword and put a value on its right side and that value will be the return value of the function.
Example: using return statement in Kotlin
fun main(){ var res = division(50, 2) println(res) } fun division (val1:Int, val2:Int):Int { return val1 / val2 }
Output:
25
Here, if we take a look at the division function, we can see that the function has a return type of Int
in its signature.
This means it is expected to receive a value of type Int from this function when it is called.
For this reason, we’ve used the return
statement in the body of the function and returned the result of dividing the value of the val1
parameter by the value of the val2
parameter.
Now we can call this function and get an integer value as a result. This value can then be assigned to other variables (for example, to the res variable in the example above).
Kotlin Local variables
A variable that you create within the body of a function is called a local variable.
A local variable is only accessible within the boundary it is defined. For example, the boundary of a function starts from the opening curly brace and ends with the related closing curly brace. This means a local variable is only accessible here and if we try to access such variable within the body of another function, we will get an error!
This is because other functions can’t see a local variable of a function!
Example: creating local variables in Kotlin
fun main(){ var fullName = "John Doe" println(fullName) sayHello() } fun sayHello(){ println(fullName) }
Output:
error: unresolved reference: fullName
Note that in this example, we got an error! This is because we have a local variable named fullName
in the body of the main function but then tried to access the same variable in the body of another function sayHello()
. This proves that a local variable is really local to its own function and any attempt to access the name of that variable in another function would cause you an error.
Global Variables in Kotlin
A global variable is a type of variable that is declared outside the body of any function!
Such a variable is called global because any function within the program can access it and change its value if necessary.
Example: Creating global variables in Kotlin
var fullName = "John Doe" fun main(){ fullName = "Jack Bauer" sayHello() } fun sayHello(){ println(fullName) }
Output:
Jack Bauer
Here, the fullName
variable is defined outside of any function. This means the variable is global and so it can be accessed within the body of any function in this program.
That’s how we could access the variable in the main function and changed its value. We also could access it in the sayHello function to send its value to the output stream.
Difference between Parameter and Argument in Kotlin
A parameter is basically the local variable of a function that we define within the signature of that function. Parameters will store the values we assign to a function when that function is called.
On the other hand, arguments are the values we assign to functions when we call them.
So think of arguments as another name for the values we pass to functions.