Johann
Johann

Reputation: 29867

Generic function in Kotlin

In Kotlin you can have a generic function like this:

fun <T> singletonList(item: T): List<T> {
    // ...
}

I don't understand what the purpose of the <T> after the fun keyword is for. The function returns List<T>, so what is the point of <T>?

Upvotes: 3

Views: 2739

Answers (2)

Mischa
Mischa

Reputation: 1333

To be able to create a generic function the compiler must know that you want to work with diferent types. Kotlin is (like Java or C#) a strongly typed language. so just passing different types into a function will make the compiler mad.

To tell the compiler that a function should be accepting multiple types you need to add a "Type Parameter"

The <T> after fun is the definition of said "Type Parameter".
Which is then used at the item Argument.

Now the compiler knows that you'll specifiy the type of item when you make the call to singletonList(item: T)

Just doing

fun singletonList(item: T) : List<T> {[...]}

would make the compiler unhappy as it does not know T.
(As long as you don't have a class named T)

You also can have multiple "Type Params" when you separate them with commas:

fun <T, U> otherFunction(firstParam: T, secondParam: U): ReturnType

Upvotes: 8

s1m0nw1
s1m0nw1

Reputation: 81859

This is a generic function which, as per the language's syntax requirements, needs to provide this part <T>. You can use it to specify T further:

fun <T: Number> singletonList(item: T): List<T> {
    // ...
}

It's also common to have multiple generic types:

fun <T: Number, R: Any> singletonList(item: T): R {
    // ...
}

Upvotes: 1

Related Questions