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

Bounded polymorphism


Functions that are generic for any type are useful, but somewhat limited. Often we will find ourselves wanting to write functions that are generic for some types that share a common characteristic. For instance, we might want to define a function to return the minimum of two values, for any values that support some notion of comparability.

We'd start by writing a function that has a type parameter representing the types of the two values being compared. But how can we compare these values, since they could be instances of anything, including Any itself? Since Any has no comparison function, we wouldn't have a way to compare the two values.

The solution is to restrict the types to those that support the functions we need to invoke; this way, the compiler knows that no matter what the runtime type of the arguments is, those functions must be available. Therefore, it allows us to invoke those functions. This is called bounded polymorphism.

Upper bounds

Kotlin supports one such...