Kotlin Functions – Making Kotlin More Modular

If you have had prior experience of programming language, you would be aware about functions.

Functions are a group of related statements which are designed to perform a specific task.

For example: a function to check if the entered number is even or odd.

Functions in kotlin are first class citizens and we declare them using the fun keyword.

Functions have 3 parts to be used effectively:

  • Declaration of Function
  • Definition of Function
  • Function Calling

Let’s have a look at what these mean to us and how to use them efficiently:

Declaration of Function

Defining the function syntax, the parameter it would accept and its return type is known as declaration of function.

Syntax:

fun functionName(<params list>) : Return Type

Example:

fun add(a: Float, b: Float): Float

In the above example, function add is accepting 2 inputs both of type float and return float.

Definition of Function

Definition in simple words means the body of the function.

Syntax:

fun functionName(<params list>) : <Return Type>{
	// Body of the Function
}

Example:

fun add(a: Float, b: Float): Float{
	var c : Float
	c = a+b
	return c
}

Calling Of Function

Function calling is pretty simple, by just passing the required number of parameters in the function name.

Syntax:

functionName(<params list>)

Example:

add(10.0,11.0)

After the parts of function, let’s understand the classification of functions in Kotlin.

Kotlin has various categories to classify function, it depends on the scope, usage, definition. Let’s have a look at the type of functions based on definition.

Types of Functions

  • Standard Functions / Built-in Functions
  • User Defined Functions

Let’s go through them individually:

Standard Functions

Functions which are predefined and can be used by the developers directly are known as standard functions.

Example: print(), max() and min() function.

These functions can be used directly by simply calling them.

User Defined Functions

Functions that a user can create or use in own project and give his own definition, like the add function we created above.

Let’s have a look below at how can we create User Defined Functions.

We can define a function using the fun keyword, followed by the function name and arguments.

fun functionName(){
	// Body of Function
}

Here, the function is created with functionName and empty parenthesis, which points the fact that function does not accept any arguments, to end inside the { } comes the body of the function.

Based on the above reading let’s try out a simple example which accepts name as input and prints a message as “Hello <Argument Value with Name>”.

fun main(args: Array<String>) {
   println("Calling function with Param : Kotlin Tutorial Blog")
   printWelcomeMessage("Kotlin Tutorial Blog ")
}

fun printWelcomeMessage(name : String){
	println("Hello $name!")
}

Output

Calling function with Param : Kotlin Tutorial Blog
Hello Kotlin Tutorial Blog !

Functions with Arguments

As seen in the example above, name is an argument or parameter which is being passed into the function, now let’s understand what can be two types of arguments: Formal Arguments and Actual Arguments.

Actual Parameters

Whenever we are calling the function, the actual variables which are passed are termed as Actual Argument or Actual Parameters.

Example:

fun main(args: Array<String>) {
	var message : String
	message ="Kotlin Tutorial Blog"   // here message variable is an actual parameter which is used in the function calling
   	printWelcomeMessage(message)
}

Formal Parameters

Now let’s see when the function is being defined:

Example:

fun printWelcomeMessage(name : String){
	// Here, name is termed as formal parameter 
	println("Hello $name!")
}

The parameters, like name in the example above which accepts the passed value from the functions calling are called formal arguments or formal parameters.

Points to Ponder in Case of Using Functions with Arguments

  1. The type of the argument needs to be mentioned explicitly. Like shown below:
fun add(num1:Integer, num2:Integer)

Here the type of numbers i.e. num1 and num2 are mentioned explicitly.

  1. We can separate two arguments by using comma (,).
  2. Data Type of Formal and Actual Parameters should be exactly same and should match in order of sequence also.

Having understood about the functions and the way functions works with arguments. That’s not all you can note that here function are not returning any value, which means that return type of the function is Unit. Unit is similar to void in Java which means that function doesn’t return any value, not even null.

Functions Returning Value

Lets move on further in User Defined functions and see how can we have a function which return some value. Below example is a simple program which will return the sum of 2 numbers using kotlin.

fun main(args: Array<String>) {
   val num1 = 15.5
   val num2 = 5.5
   val result: Int
   result = sum(num1, num2)
   println("Sum of 2 numbers: $num1 and $num2 is:- $result")
}

fun sum(value1: Double, value2: Double): Int {
    val sum = value1 + value2
    val sumInteger = sum.toInt()
    return sumInteger
}

Output

Sum of 2 numbers: 15.5 and 5.5 is:- 21

Here the point worth noting was the return type of the function sum. The sum function here was returning Int value.

How to make function return a value?

We can define functions which can return value by simply passing the data type of the expected value as shown in the example above. The syntax would look something as below:

fun functionName() : <Data Type of Return Value>{
	// Body Of Function
}

Single Expression functions

What if there are functions in the cases when the function have only single expression to be executed like below:

fun main(args: Array<String>) {
    println(printName("Kotlin", "Blog"))
}

fun printName(fName: String, lName: String): String = "Hello $fName $lName!"

Output

Hello Kotlin Blog!

Here, as you can see that we have removed curly braces { }  from the function body to provide to ease the code and make it look more simple.

In the case above since the expression evaluation can be done at the time of compilation it is evident that the return type of the function even if not mentioned explicitly can be worked upon by the system, like below:

fun main(args: Array<String>) {
    println(printName("Kotlin", "Blog"))
}

fun printName(fName: String, lName: String) = "Hello $fName $lName!"

The compilation of the above program gives the same output again:

Hello Kotlin Blog!

After having covered the basics of functions it’s important for us to understand other types of function which we will be using on daily basis.

Let’s understand the classification of function on the basis of scope of functions, unlike Java, Kotlin allows functions to be defined at the top level. Let’s see the different types functions based on the scope.

Functions Based on Scope

  1. Top Level Functions: These functions are placed on the top of the stack and are not needed to be enclosed inside a class.
  2.  Member Functions: Functions which can be defined inside a class.
  3. Local or Nested Functions: Functions defined inside a function.

Let’s see and understand them with examples one after the other.

Top Level Functions

As the name suggests, the functions which are defined directly and are not enclosed within a class are termed as Top Level Functions.

The most common example of Top Level Function is the main() functions,  we can place main function directly inside the file and it is not necessary to have it placed inside a class like java.

All the functions we have used above are Top Level Functions since those were not placed inside any class.

We can define the function directly inside the package and it can be used to call directly using the function name, in case when we want to call the package from outside we can simply do it calling packagename.functionName.

Member Functions

Functions which are defined inside the class and can be attributed as the property of class are termed as member functions.

We can access or call the member functions by using the object of the class.

They can be called using the dot (.) operator, for example : For an Employee class with object emp having function as displayEmployeeName() can be done as :

emp.displayEmployeeName()

We will discuss more about them when we will see class and object in upcoming tutorials.

Nested Functions

Kotlin allows you to define function inside functions and these can be accessed only inside the parent function. Such function are known as nested functions or local functions.

The use of having nested functions is to make code more encapsulated and make the program more readable and simple to understand. Interesting thing to know here is that we can use all the local variables of the outer functions.

The process of declaration and definition of all of these functions would remain same, the only difference is the place where the definition of function.

So, that was the basis of functions in Kotlin and we discussed about the main parts of kotlin and the basic function classification based on the definition of the function, well there’s still more to come as we have further interesting reads in terms of single line functions, anonymous functions, infix and recursive functions and lambda expressions. Stay tuned as we bring along those in the upcoming tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *