Functions in Kotlin


What is Functions in Kotlin ?
Functions are nothing but kotlin code written under a block to perform a task whenever user want to perform by making a call to the this block of code, and this block of code is called as function in kotlin.

Function are defined using fun keyword with optional parameters and a return value. If return value is not specified, then by default kotlin sets the default return value as Unit.< br>
functions-in-kotlin

Calling a function uses a traditional approach, we just provide the name and parentheses like below


fun multiply(value:Int){
	println("This code multiplies the values")
}
// calling a function
multiply(3)			

If the Functions is part of a class then we have to use constructor of the class to invoke the function, we will discuss more about constructor in later charts.


fun main(args:Array<String>)
{
	ABC().multiply()
}
class ABC{
	fun multiply(){
		println("this code multiplies the values")
	}
}		

In above code ABC is class name and ABC() is constructor , both class and constructor will have same name and the only difference is () is used along with constructor.

In other words, people may say like creating instance and calling the function, the function which are present inside a class are called as member functions.

There are few types of functions are available in kotlin, which are :

Single Expression Functions


What is single expression functions ?
Single line/expression function are the ones which have only one line of kotlin code and this will return values. Most of the time single line functions omits the braces but you can include if you want, I would recommend not include braces.

Single line/expression functions uses = (assignment) operator rather than using the return keyword for returning value. The return value is inferred by kotlin compiler.


fun multiply(value:Int) = value * value		

Same function with braces


fun multiply(value:Int){
	return value * value	
}	

Single line functions are easy to read and if you want you ca include the return value type.


fun main(args:Array<String>)
{
    var result = ABC().multiply(3)
    println(result)
}
class ABC{
    fun multiply(value:Int):Int = value * value
}	

Unit Functions in Kotlin


What is Unit Functions in kotlin ?
If a function doesn't return any value, then compiler makes it to Unit return type . Every function must return value either other value or Unit values.

It is not mandatory to specify the return type Unit in kotlin


fun multiply(value:Int){
	return value * value	
}	

Function's return type is Unit explicitly


fun multiply(value:Int):Unit{
	return value * value	
}	

Operator Overloading in kotlin

Parameters in Kotlin Functions

Parameter are nothing but the input values for the functions

Functions may or may not alter the value of the provided parameters. If we pass variable as parameters to a function, these variables will be resolve at the function call itself so the function will receive only values but not their references of the variables.

Parameter are optional, and the parameters must be covered by parentheses (), and separated with comma,

User must specify the type of the parameters explicitly, compiler may not infer the types for parameters, but you may try 'Any' type if you don't know the parameter type or if you expect more than one type of parameter for same functions

multiply() function accepts two Int parameters and return Int value.


fun main(args:Array<String>)
{
    var abc = ABC().multiply(3, 5)
    println(abc)
	println("***************************")
	
	justPrint(10.99)
	justPrint("karthiq")
	justPrint(true)
}
class ABC{
    fun multiply(value:Int, value2:Int):Int{
		return value * value2
	}
}
// accepts all type of values
fun justPrint(tobePrintend:Any){
	println(tobePrintend)
}	

Parameters with lambda

Top Level Functions

Kotlin's Top Level Functions are defined outside of any class, object, or interface

Top level functions are defined inside the file, so far we have seen example of main and main was not part of any class or interface. SO main is one of the Top Level functions.

We call these function as top level functions as these have more hierarchy level compared with classes, interfaces, or functions in class and interfaces.

You can write the top-level functions when it does not make any sense if you a add them inside a class or interface, or when this function is odd one and does not belong to a group.

You also write utility functions as top-level functions in kotlin, these are similar to static methods in java as there is no such thing as static in java.

You can call the top-level function directly by calling their name and passing parameters.

In Below code justPrint function is top-level function in kotlin file.


fun main(args:Array<String>)
{
	justPrint("karthiq")
}
// accepts all type of values
fun justPrint(tobePrintend:Any){
	println(tobePrintend)
}	

Constructors in kotlin

Member Functions in Kotlin

A member function is function defined inside a class, object or an interface in kotlin

We should create object for the class to call the member functions

Member functions are present inside a class, so we have to call the function with help of object, object for a can be created by calling constructor.

As of now think, constructor is nothing but class name with parentheses (), I have dealt with constructor in different chapter. In below code multiple is member functions or you call it as class level functions as well, ABC is class name, ABC() creates the object for class called ABC.


fun main(args:Array<String>)
{
    var abc = ABC().multiply(3, 5)
	println(abc)
	
	var xyz = ABC()
    println(xyz.multiply(3, 3))
	
}
class ABC{
    fun multiply(value:Int, value2:Int):Int{
		return value * value2
	}
}
	

Calling Member functions from another member function

If you want to call the member function from another class's member function then you must use the above object creation and calling the function way

But if you have more than one member functions in same call and if you wish to call other member functions(from same class's functions) then you can directly call them by their name.


fun main(args:Array<String>)
{
    var abc = ABC().multiply(3, 5)	
}
class ABC{
    fun multiply(value:Int, value2:Int):Int{
		addition()
		return value * value2
	}
	fun addition(){
		println("this example for calling a function from same class's members")
	}
}
	

Getters and setter

Local Functions in Kotlin

Kotlin's Local functions are defined inside functions

Anything outside the function cannot access the local functions but local functions can access all the objects just like normal functions.

We can achieve this local functions effect by creating a private function but class level member can access private function but only outside function can access the local functions.

Local functions are useful when you are writing very large functions in kotlin, you can call local function by calling their name.


fun main(args:Array<String>)
{
    var a =10
    var b =3
    fun localFunctionExample():Int{
        println("You called local function")
        return a * b
    }
    localFunctionExample()
}	

Obviously there are limitations for local class, lets see them.

You cannot use a variables those are declared after the function definition.


fun main(args:Array<String>)
{
    fun localFunctionExample():Int{
        println("You called local function")
        return a * b
    }
	var a =10
    var b =3
    localFunctionExample()
}

You cannot call the local function before defining the local function.


fun main(args:Array<String>)
{
	var a =10
    var b =3
    localFunctionExample()
    fun localFunctionExample():Int{
        println("You called local function")
        return a * b
    }
}

You can nest more and more functions inside a function.


fun main(args:Array<String>)
{
	var a =10
    var b =3
    fun localFunctionExample():Int{
        println("You called local function")
		
		fun innerLocalFunctionExample(){
			println("********inner local function************")
		}
		innerLocalFunctionExample()
        return a * b
    }
	localFunctionExample()
}

this() & super() in kotlin

Calling a function

By now, you might be aware how to call but let me explain it one more time. You can call a top-level function just with name and arguments like below.


fun main(args:Array<String>)
{
	justPrint("karthiq")
}
// accepts all type of values
fun justPrint(tobePrintend:Any){
	println(tobePrintend)
}	

You can call the member functions in other classes using the object/instance of the class


fun main(args:Array<String>)
{
    var abc = ABC().multiply(3, 5)	
}
class ABC{
    fun multiply(value:Int, value2:Int):Int{
		return value * value2
	}
}
	

Named Arguments in Kotlin Functions:

Names arguments in kotlin are values we provide when we call a function with their names. So far, I have used examples without using the names of the arguments.

In simple terms, we provide the arguments by assigning them to the parameter names in a function.


fun main(args:Array<String>)
{
	// this is non-names argument.
	justPrint("karthiq")
	
	// named argument
	justPrint(tobePrintend = "karthiq")
}
// accepts all type of values
fun justPrint(tobePrintend:Any){
	println(tobePrintend)
}	

Once you name arguments then you should name all the arguments in the call
    Benefits of Named arguments with Kotlin :
  • Better readability of the program
  • Avoids confusion
  • Easy to understand the intent of the function
  • You don't have to follow the order of arguments when you use named arguments

fun main(args:Array<String>)
{
	// named arguments
	justPrint(name = "karthiq", websiteName="CherCher.tech")
	println("**********************')
	// position of  arguments changed
	justPrint(websiteName="CherCher.tech", name = "karthiq")
}
fun justPrint(name:String, websiteName:String){
	println("Person name is  : $name")
	println("Website name is  : $websiteName")
}	

Difference between Arguments and Parameter of Function :

Arguments are the values used while calling the function, Parameter are the variables(kind of) declared with function signature. difference-between-argument-parameter-kotlin Most of the time These two are called interchangeably.

Enum with Properties and functions

Default Parameters in Kotlin Functions

Default parameters provides a value when user ignores to provide arguments to the functions. These are useful when you have same value for the parameter in most of the places.

In Simple terms, In India when you are applying for voter id ( used for voting purpose in elections ) most of the people have nationality as India, so Systems will have default value for nationality as India but there are people who have French(Pondichery) citizenship and Anglo-Indians as well, so only in those cases they have to override Nationality. So by having default value will reduce the burden (little bit).

While creating/defining a function, we have to provide the value for the default parameter using assignment operator '=', it is not mandatory to have default parameters


fun main(args:Array<String>)
{
    // only name is provided
    getVoterID(name = "karthiq")
    println("**********************")
    // name and nationality are provided
    getVoterID(name = "Peter Parker", nationality="French")
}
fun getVoterID(name:String, nationality:String="Indian"){
    println("Person's name is  : $name")
    println("Person's  Nationality is  : $nationality")
}

I know Spider-man is not French :)

Once you create default parameter then you should name all the parameters in the definition

Kotlin Generics with Classes

Vararg in functions of Kotlin

Vararg is a supportive type(not data type) for variables in function declaration, Vararg is makes the function to accept the n-number of parameters without specifying each of them in function declaration in kotlin.

Vararg is a keyword and it also known as variable number of arguments.


fun main(args:Array<String>)
{
   // using vararg
    justPrint("karthiq", "one", "two", "three")
}
fun justPrint(name:String, vararg numberAsWords:String){
    println("The name is $name")
    for(element in numberAsWords){
        println(element)
    }
}

Internally when you pass number of parameter for the vararg variable, kotlin compiler converts the parameter for the vararg into array after accepting the parameter at function level.

You might have a question in mind that why cannot I pass array to vararg ?, the answer is you can :), but vararg will not accept array as value, vararg accept only individual elements vararg-kotlin-functions

Let me draw a image for above justPrint function varargs-functions-kotlin

Vararg could hold any position in the parameter list, but if vararg position is other than last in kotlin, then you must specify the arguments after vararg with names while calling the function, I mean they should be named arguments, otherwise compiler will show error to pass the arguments after the vararg


fun main(args:Array<String>)
{
   // using var arg
    justPrint("karthiq", "one", "two", "three", website="chercher.tech")
}
fun justPrint(name:String, vararg numberAsWords:String, website:String){
    println("The name is $name")
    for(element in numberAsWords){
        println(element)
    }
    println("The website if : $website")
}

I would recommend you to write the vararg as last parameter

Spread Operator (*) with vararg:

Spread operator(*) is used to scatter the array into individual element

so that vararg can accept the parameter, vararg cannot accept array as parameter for it, because of which we would be using the spread operator(*).

spread-kotlin-operator

Let's re-write the above example with spread operator.


fun main(args:Array<String>)
{
    var sampleArray = arrayOf("one", "two", "three")
   // using var arg
    justPrint("karthiq", *sampleArray)
}
fun justPrint(name:String, vararg numberAsWords:String){
    println("The name is $name")
    for(element in numberAsWords){
        println(element)
    }
}

spread-operator-kotlin

Reflection in kotlin

Kotlin's Extension Functions

Extension functions are functions that, help us to extend the functionality of classes without having to touch their code. We can create extension function to the class, to which we don't have source code as well.

Kotlin extension functions allow you to add functionalities/behaviour to a class without the need of getting to its source code, since an extension function can be declared outside the scope of its class.

You just need write a function as you would normally, and put the name of the class before function name separated by a dot(full stop).

Extension functions can be written without even having a Class in kotlin file, I mean extension function could be a top level functions, it can also be Member function but not a local function(nested function).

In Other Languages : Extension functions are similar to extending a Class and providing some new functionalities in Sub class functions in Other languages.

Let me put it in Simple terms: You have created a class for handling the login function in your code and fortunately you have got good offer in some company and you left the Job. While leaving the job just because of frustration you have deleted the source code (not byte code) of the Login class and you moved out of company.

Now new guy joins the company, but he is not able to find the source code, but somehow he is able to find the Byte code. Company have received some Spam/robot logins, so company wants to have a captcha at login page, So do you think that the new guy should develop new code for login and captcha as part of new Login class(you have deleted old src code), or would you suggest to use the bytecode of the existing Login class and write new class for captcha, most of the people would suggest him the same.

Just think if there is a way to add new captcha functionality to Login class without having the Login class source, wouldn't be great ?. Yes, this feature is what called as extension function in Kotlin.

Syntax of Extension Functions: extension-function-kotlin

You must create object of the class to call the extension function.

In below example, I am creating extension function for String class called add, this function would add two numbers and print the result.


fun main(args:Array<String>)
{
	// calling extension function
    "someString".add(10, 20)
}
fun String.add(a:Int, b:Int){
    var result = a +b;
    println("The total is : $result")
}

If you want more real time example let's consider below example.


fun main(args:Array<String>)
{
	var carSpeed = Car()
    carSpeed.reverse();
}
class Car(){
    fun speed1(){
        println("Car is running speed level 1")
    }
    // some function like speed2, speed 3
    fun speed5(){
        println("Car is running speed level 1")
    }
}
fun Car.reverse(){
    println("Car is running in reverse")
}

Extension functions are statically dispatched :

All the extension function calls are matched with respective functions on compile time itself, so the dispatching occurs at compile time and it is called as static dispatching

Rules for Extension functions :

  • You cannot override a member function

Scope of Extensions functions:

You can directly access the top level extension function in same file without any import. But when you are trying to access the extension function in some other file then you should import the functions.

Read Properties File in Kotlin

infix functions in Kotlin

infix functions are nothing but the regular Class functions but accepts only one parameter and defined using infix keyword, when you use the infix notations you must need to have two Operands,

  • Object/instance in which the infix function is present
  • The function parameter.

syntax-infix-function-kotlin

Infix function could be extension functions or class functions, you cannot use infix notation with top level or nested functions

I will denote whenever we go across the infix function in future lessons, lest see the infix functions we can across already.

You can use normal function calls to infix functions but you cannot use infix calls to normal functions .

On Kotlin Control flow chapter We have discussed about range functions like range(), downTo, there we have used the infix notation, like below.

In below example, downTo is infix function, 9 is the Object and 3 is the parameter


fun main(args:Array<String>)
{
	// using as infix functions
    for(valFun in 9 downTo 3){
        println(valFun)
    }
	println("***************")
	// not using as infix functions
	for(valFun in 9.downTo(3)){
        println(valFun)
    }
}


fun main(args:Array<String>)
{
    // using object directly
    InfixFunctionExample() justPrint "karthiq"
    println("***************************")
    // using stored object
    var infixExample = InfixFunctionExample()
    infixExample justPrint "chercher tech"
	println("============================")
	infixExample.justPrint("chercher tech")
	
}
class InfixFunctionExample{
    infix fun justPrint(tobePrinted:String){
        println("I am here to print : $tobePrinted")
    }
}

Apache Commons CSV Integration

Static functions in Kotlin

If you come from Java world, you are already familiar of static methods. You were able to access static variables/member using class reference in java.

There is no static concept in Kotlin programming language, but Kotlin provides few ways to achieve this static features.

Kotlin recommends the user to use top-level function in the pace of static functions as the top level functions represent the static functions, you can see the relationship when view the decompiled code of kotlin.


fun justPrint(){
    println("Top level function in kotlin")
}
fun main(args:Array<String>)
{
   justPrint()
}

Decompiled code for the above kotlin program (you can view it by Navigating on IntelliJ Tools ->Kotlin ->View Decompile kotlin to Java) decompile-kotlin-to-java


public final class FirstKotlinUsageKt {
   public static final void justPrint() {
      String var0 = "Top level function in kotlin";
      System.out.println(var0);
   }
   public static final void main(@NotNull String[] args) {
      Intrinsics.checkParameterIsNotNull(args, "args");
      justPrint();
   }
}

From above code you see the top level function is converted into static function in java.

Object keyword to create static functions in Kotlin :

Instead of using class you can use the object keyword and then you can write the functions and these functions can be accessed using the Object name.

Any functions or variable under object declaration will work as static function or variable.


fun main(args:Array<String>)
{
    StaticFunctionExample.justPrint()
}
object StaticFunctionExample{
    fun justPrint(){
        println("Static kind of function in kotlin")
    }
}

In above style we are using object only rather than class to make the functions as static but if you want to write the function as like in java static then you should use companion object in Kotlin.

Companion Object block in Kotlin to create Static Functions:

Companion Object makes all the variables/functions present inside the block as static members of the kotlin class. You can use same style as Java to call these functions/variables present in the companion object block of kotlin.

I am re-writing the above example using the companion object, you can call the static function either using Companion keyword or without using it.


fun main(args:Array<String>)
{
    StaticFunctionExample.Companion.justPrint()
    println("******************")
    StaticFunctionExample.justPrint()
}
class StaticFunctionExample{
    companion object {
        fun justPrint(){
            println("Companion Object Static Function")
        }
    }
}

Companion Object with Name :

Sometimes, you might provide name to the companion object in kotlin in those cases you cannot use the Companion keyword while calling the static function, so in those cases you call the static function by using the class name or using the companion object name.


fun main(args:Array<String>)
{
    // calling using the companion object name
    StaticFunctionExample.NameOfCampanion.justPrint()
    println("******************")
    StaticFunctionExample.justPrint()
}
class StaticFunctionExample{
    companion object NameOfCampanion{
        fun justPrint(){
            println("Companion Object With name Static Function")
        }
    }
}

Create Static function using @JvmStatic in Kotlin :

If you want to get rid of Companion identifier, and also don't want to give any name to your object, you need to place @JvmStatic annotation with the function name.

But actually I did not feel much difference between @JvmStatic and Companion Object function.


fun main(args:Array<String>)
{
    StaticFunctionExample.Companion.justPrint()
    println("******************")
    StaticFunctionExample.justPrint()
}
class StaticFunctionExample{
    companion object {
        @JvmStatic
        fun justPrint(){
            println("@JvmStatic Static Function")
        }
    }
}

Enum with Properties and functions

Basic Questions about Kotlin functions

kotlin function without return

In kotlin, we may or may not return a value in functions, if we don't return any value in kotlin function the kotlin compiler writ Unit return type to that function.

Functions return Unit only when there is not return type or when user specifies Unit as return type.

kotlin function vs method

In java we have called block of code as method but in kotlin we call the methods as functions( like in C). So methods and function both references same thing.

may be sometime when you write java code in Kotlin program you might call a function as method.

kotlin functions as parameters

In Kotlin, a function can be passed as a parameter or can be returned from a function, the function which does the same is known as a higher-order function.

In other words, a higher-order function is a function that takes functions as parameters or returns a function.

kotlin function named argument

In kotlin function you can provide value by providing the parameter names, to make the program much readable

When you are using named parameter you can change the positions of the parameter

kotlin boolean function

Kotlin types functions are nothing but the function which return a specific type of return value. So boolean function are function which will return boolean value.


fun flyTheCar():Boolean{
    println("Not possible to fly the car")
	return false
}

kotlin call function by name

You can call a function by their name, when the function is a top level function, that mean target function is not part of any class.

If you are calling a Class function from another function in same class then you can call it by the function name.

you can call the local or nested function with its name in the outer function.

If you want to call a class function from another class then you cannot directly call the function with its name but you can call it by creating object to the class

kotlin function composition

Unlike many other languages, Kotlin does not have any built-in support for function composition. However, it is very easy to add our own using the facilities we have seen so far for manipulation of functions.


fun main(args: Array<String>) {
    val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))
}
fun isOdd(x: Int) = x % 2 != 0
fun length(s: String) = s.length
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
    return { x -> f(g(x)) }
}

kotlin function variable declaration

We can have variable in functions and these are limited to that functions only, outside function cannot access them and these variables are called as local variables.

kotlin function expression

Sometimes in Kotlin functions are used for single expression, these functions will not have more than one line of code. Single line expression functions will not have return keyword but they will return the assignment value on right side.

fun square(k: Int) = k * k

kotlin package level functions

package level functions are nothing but top level functions, top level functions are declared outside the classes in kotlin file

kotlin function main not found

basically this error means, kotlin compiler is not able to find the main function in the file, because of following reason it could happen.

  • main function is not at all created by you
  • main function is present inside a Class
  • main function arguments are having difference from the expected arguments

kotlin member functions

Kotlin member functions are nothing but functions present inside a class.

kotlin mutable function parameter

No, kotlin does not support mutable Parameters and if it allows then there is huge chance for bugs and security threats.

kotlin function return multiple values

Kotlin allows user to return only one value, but you can use arrays and lists, set for returning multiple values.

kotlin native function

The concept of a library, a collection of functions and other resources such as images, to be used by applications is available in Kotlin/Native and it is represented as a file with the extension klib.

Kotlin/Native libraries are artifacts that are only available at compile time, i.e. we do not ship these as dependencies to our application (as we would for instance with DLL files on the Windows platform).

Kotlin: Pure function

To say a function is pure, it should have the following qualities.

  • It should depend only on the input to produce the result, not on any hidden information or external state.
  • It shouldn’t cause any observable side effects, like modifying a parameter passed by reference or global variable/object.

fun getSum(a:Int,b:Int):Int{
    return a+b
}

As You know pure function doesn't depends on any external state or object, it becomes easier to test pure function in kotlin.

kotlin partial function

Currying turns a function into a chain of functions. Partial application lets you 'fix' certain parameters to a function, resulting in a new function.


val curried: (Int) -> (Int) -> (Int) -> Int = { i1 -> { i2 -> { i3 -> i1 + i2 + i3 } } }
val partial: (Int) -> (Int) -> Int = curried(2)		

add is a function that returns a function that takes an int, and returns an int. Internally, that function is defined as a + b.


fun add(a:Int) : (Int) -> Int {
    return { b: Int -> a + b }
}	

Static functions in Kotlin

We can achieve the same effect as Static function in kotlin using Companion object


class Foo {
  companion object {
     fun a() : Int = 1
  }
}
								
// you call it with 
Foo.a()	

Smart cast Operator [as?]

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group