Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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 parameter...