0
0
Kotlinprogramming~5 mins

Generic constraints with where clause in Kotlin

Choose your learning style9 modes available
Introduction
Generic constraints with where clause help you tell the computer what kind of data your function or class can work with. This keeps your code safe and clear.
When you want a function to accept only certain types of data, like numbers or text.
When you have a class that should only work with types that have specific features.
When you want to combine multiple rules for the types your code can use.
When you want to make your code flexible but still safe from errors.
When you want to reuse code for different data types but with limits.
Syntax
Kotlin
fun <T> functionName(param: T) where T : SomeClass, T : SomeInterface {
    // function body
}
The declares a generic type named T.
The where clause sets rules that T must follow, like being a subclass or implementing an interface.
Examples
This function only accepts types that are or inherit from Person, so it can use the name property.
Kotlin
fun <T> printName(item: T) where T : Person {
    println(item.name)
}
This function works with types that can be compared, like numbers or strings.
Kotlin
fun <T> compare(a: T, b: T) where T : Comparable<T> {
    if (a > b) println("a is bigger")
}
This function accepts types that are numbers and can be compared.
Kotlin
fun <T> process(item: T) where T : Number, T : Comparable<T> {
    println(item.toDouble())
}
Sample Program
This program defines a Person class and a greet function that only accepts Person or its subclasses. It prints a greeting using the person's name.
Kotlin
open class Person(val name: String)

fun <T> greet(person: T) where T : Person {
    println("Hello, ${person.name}!")
}

fun main() {
    val p = Person("Alice")
    greet(p)
}
OutputSuccess
Important Notes
You can add multiple constraints separated by commas in the where clause.
The where clause is useful when constraints are complex or when you want to keep the generic declaration clean.
If you only have one simple constraint, you can put it directly after the generic type like .
Summary
Generic constraints with where clause limit the types a generic can accept.
They help keep your code safe by ensuring the types have needed features.
Use where clause to add multiple or complex constraints clearly.