0
0
Kotlinprogramming~5 mins

Type constraints with upper bounds in Kotlin

Choose your learning style9 modes available
Introduction
Type constraints with upper bounds help you tell the program to only accept certain types that share common features. This keeps your code safe and clear.
When you want a function to work only with types that have a specific property or behavior.
When you write a class that should only handle objects that follow a certain rule.
When you want to reuse code but limit it to types that can do certain actions.
When you want to avoid errors by restricting types to those that support needed operations.
Syntax
Kotlin
fun <T : SomeType> functionName(param: T) { 
    // code using param
}
The means T must be SomeType or a subtype of it.
You can use multiple constraints with where clause if needed.
Examples
This function accepts any type that is a Number or inherits from Number.
Kotlin
fun <T : Number> printDouble(value: T) {
    println(value.toDouble() * 2)
}
Here, T must be a non-null type (Any is the root of all non-null types).
Kotlin
fun <T> copyItems(source: List<T>, destination: MutableList<T>) where T : Any {
    for (item in source) {
        destination.add(item)
    }
}
This class only accepts types that can be compared with themselves.
Kotlin
class Box<T : Comparable<T>>(val value: T) {
    fun isGreaterThan(other: T): Boolean {
        return value > other
    }
}
Sample Program
This program defines a function that returns the bigger of two values. It only works with types that can be compared, like numbers or strings.
Kotlin
fun <T : Comparable<T>> maxOfTwo(a: T, b: T): T {
    return if (a > b) a else b
}

fun main() {
    println(maxOfTwo(5, 10))
    println(maxOfTwo("apple", "banana"))
}
OutputSuccess
Important Notes
Upper bounds ensure your generic types have the features you need.
You can use multiple upper bounds with syntax like where T : A, T : B.
If you don't specify an upper bound, Kotlin uses 'Any?' by default, which allows any type including null.
Summary
Type constraints with upper bounds limit generic types to certain classes or interfaces.
They help make your code safer by ensuring needed functions or properties exist.
Use the syntax to set an upper bound on T.