Parameterised functions
Consider a function called random()
that, when given some elements, returns one element randomly. We don't need to know what the types of the elements are when we write this function, as we will not be using the elements ourselves. We just need to be able to select one to return. When we use a type in this way - abstracting over the type, we use the term type parameter. So, our random function would have a single type parameter: the type of the elements we are selecting from.
If we want to write a generic function, like the random()
function just mentioned, we might decide to start with something like this:
fun random(one: Any, two: Any, three: Any): Any
This would work as we can pass in any instances we choose. However, no matter what types we choose to pass in as arguments, our returned type would be inferred as Any
. We'd then be forced to cast back to the original type, and this is error prone, not to mention ugly.
We can do better with a type...