# When (and when not) to Use Type Parameter Constraints in Kotlin

DevFeed: [When (and when not) to Use Type Parameter Constraints in Kotlin](<https://devfeed.tech/articles/when-and-when-not-to-use-type-parameter-constraints-in-kotlin-25046.md>)

Original publisher: [Read original article](<https://typealias.com/guides/when-to-use-type-parameter-constraints/>)

Author: author@typealias.com (Dave Leeds)

Published: 2017-10-01T20:19:28Z

Content type: tutorial

Language: en

Sources: [Dave Leeds on Kotlin - typealias.com](<https://devfeed.tech/sources/dave-leeds-on-kotlin-typealias-com.md>)

Topics: [Kotlin](<https://devfeed.tech/topics/kotlin.md>), [generics](<https://devfeed.tech/topics/generics.md>), [Code](<https://devfeed.tech/topics/code.md>), [Cheat sheet](<https://devfeed.tech/topics/cheatsheet.md>)

Tags: [article](<https://devfeed.tech/tags/article.md>), [cheat-sheet](<https://devfeed.tech/tags/cheat-sheet.md>), [code](<https://devfeed.tech/tags/code.md>), [generic](<https://devfeed.tech/tags/generic.md>), [generics](<https://devfeed.tech/tags/generics.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [parameter](<https://devfeed.tech/tags/parameter.md>), [programming](<https://devfeed.tech/tags/programming.md>), [reference](<https://devfeed.tech/tags/reference.md>), [type-parameter](<https://devfeed.tech/tags/type-parameter.md>), [types](<https://devfeed.tech/tags/types.md>)

## AI overview

This Kotlin tutorial explains how type parameter constraints limit the types accepted by a generic function. It shows how an upper bound lets the function invoke shared properties while preserving the specific return type, and outlines when constraints are useful.

## Source excerpt

Kotlin allows you to constrain a type parameter on a generic when you declare it, limiting the range of types that it can accept. Why is this helpful? Well, let's take a look at an example. Let's say you've got a few pets at home, and you want to pick a favorite: fun <T> chooseFavorite(pets: List<T>): T { val favorite = pets[random.nextInt(pets.size)] // This next line won't compile - because `name` can't be resolved println("My favorite pet is ${favorite.