1

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>?

1

2 Answers 2

5

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
4
  • 1
    Still isn't clear. The function already has a type parameter (item: T).
    – Johann
    Mar 8, 2019 at 9:01
  • 3
    no if you only would write func funcName(item: T) the compiler would be mad at you because it does not know T... Thats why you need the <T> in front. That is what tells the compiler that T is a TypeParam. (item: T) is the usage and <T> is the definition
    – Mischa
    Mar 8, 2019 at 9:02
  • OK. So how would do define a function that has 3 parameters and the first and last one are types T and U?
    – Johann
    Mar 8, 2019 at 9:06
  • fun <T, U> funcName(firstParam: T, second: AnotherType, third: U): ReturnType
    – Mischa
    Mar 8, 2019 at 9:08
1

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 {
    // ...
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.