Kotlin Generic Functions Tutorial

In this section, we will learn what the Generic Functions are and how to use them in Kotlin.

Note: we’re assuming you’re already familiar with the Kotlin Generic Classes.

What is Generic Function in Kotlin?

In Kotlin, functions alone can become generic as well!

Basically, you can create a function with generic type outside of any class or inside of a non-generic class. This way, we can use the generic type name of the function for the data type of parameters and also its return type.

Now let’s see how to create a generic function.

How to Create a Generic Function in Kotlin?

This is how we can create a generic function in Kotlin:

fun <T> functionName(param:T, param2:data-type):T{…}

The generic name and the angle brackets comes after the fun keyword and before the name of the target function.

Now we can use this generic name /names as the data-type for the parameters of the function or as the return data type of the function.

Example: creating a generic function in Kotlin

class SimpleClass{
    fun <T> details(param:T){
        println("The value of the parameter is: $param")
    }
}
fun main(){
    var simp = SimpleClass()

    simp.details<String>("Jack")
    simp.details(10)
}

Output:

The value of the parameter is: Jack

The value of the parameter is: 10

How does generic function work in Kotlin?

In this example, the class SimpleClass is a non-generic type, but we can see there’s one generic function in its body which used the generic name as the data type for the parameter of the function.

Now, when creating an object from this class, in order to call the generic function, we need to set the data type for the generic name right at the function call.

For example:

simp.details<String>(“Jack”)

Note that here we’ve set the data type as String and that means the generic name will be replaced with the String data type.

Other than explicitly setting the data type of a generic function, Kotlin is capable of inferring the data type by checking the type of the value we set as the argument for the function.

For example, in the second call to the details() function, we just passed the number 10 as the argument and didn’t set any type for the generic type name explicitly! So Kotlin will check the type of the argument and see that the type is Int, hence replaces the generic type name with the Int data type.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies