Generic Constraints
Bound type parameters.
Generic Constraints is a free Kotlin Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.
Constraining Type Parameters
Sometimes a generic must accept only certain types, for example types that are comparable or that subclass a base. Generic constraints set an upper bound on a type parameter.
The Default Upper Bound
Without a constraint, a type parameter's upper bound is Any?, so it accepts any type including nullable ones. To allow only non-null types, bound it to Any.
fun <T : Any> requireNonNull(value: T): T {
return value
}
fun main() {
println(requireNonNull(42))
}A Single Upper Bound
Use T : Bound to require that T be a subtype of Bound. This lets you call the bound's members inside the function.
fun <T : Number> sumDoubled(a: T, b: T): Double {
return a.toDouble() * 2 + b.toDouble() * 2
}
fun main() {
println(sumDoubled(3, 4))
println(sumDoubled(1.5, 2.5))
}Comparable Bound
A common bound is Comparable<T>, which lets you compare elements with <, >, or compareTo.
fun <T : Comparable<T>> maxOf2(a: T, b: T): T {
return if (a > b) a else b
}
fun main() {
println(maxOf2(3, 9))
println(maxOf2("apple", "banana"))
}Calling Bound Members
Inside a constrained generic, the compiler knows T has the bound's API, so you can call those methods directly without casting.
fun <T : CharSequence> describe(value: T): String {
return "Length is ${value.length}"
}
fun main() {
println(describe("hello"))
println(describe(StringBuilder("hi")))
}Multiple Bounds with where
For more than one bound, use the where clause. T must then satisfy ALL listed constraints.
fun <T> copyWhenValid(value: T): T
where T : CharSequence, T : Comparable<T> {
return value
}
fun main() {
println(copyWhenValid("text"))
}Bounds on Classes
Constraints work on generic classes too, restricting what types the class can be instantiated with.
class NumberBox<T : Number>(val value: T) {
fun asDouble(): Double = value.toDouble()
}
fun main() {
val box = NumberBox(10)
println(box.asDouble())
}Constraint Enables Operations
The whole point of a constraint is to unlock operations. Without T : Number you could not call toDouble(); the bound guarantees the method exists.
Non-Null Bound in Practice
Bounding to Any rejects nullable arguments at compile time, a handy way to require non-null generics.
fun <T : Any> firstNonNull(a: T, b: T): T = a
fun main() {
println(firstNonNull("x", "y"))
// firstNonNull(null, "y") would not compile
}Combining with Variance
Constraints and variance solve different problems: variance (in/out) controls subtyping relationships, while constraints (: bounds, where) restrict which types are allowed. They can be used together.
Designing Good Constraints
Add a constraint only when you need a capability from the type. Over-constraining reduces reusability; under-constraining forces casts. Bound to the most general type that provides the operations you use.
Quick Check
How do you require a type parameter to satisfy more than one bound?
Recap
Generic constraints set upper bounds with T : Bound (or where for multiple bounds), unlocking the bound's operations and excluding incompatible types. Bounding to Any requires non-null. Combined with variance, constraints let you design safe, expressive generics. This completes the Generics and Variance course.
Learn Kotlin with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Generic Constraints” lesson free?
Yes — any 3 lessons of the Kotlin Academy learning path, including “Generic Constraints”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.
What will I learn in “Generic Constraints”?
Bound type parameters. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
How long does the “Generic Constraints” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Generic Functions and Classes
- Declaration-Site Variance
- Use-Site Variance
- Generic Constraints