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