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.
fun <T> functionName(param: T) where T : SomeClass, T : SomeInterface { // function body }
fun <T> printName(item: T) where T : Person { println(item.name) }
fun <T> compare(a: T, b: T) where T : Comparable<T> { if (a > b) println("a is bigger") }
fun <T> process(item: T) where T : Number, T : Comparable<T> { println(item.toDouble()) }
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) }
where clause in Kotlin generic constraints?where clausewhere clause allows specifying multiple or complex constraints on a generic type clearly and separately from the main declaration.where clause in Kotlin?where clause follows the generic parameter list and uses commas to separate constraints.where T : Comparable<T>, T : Serializable. Others have syntax errors or misplaced keywords.fun <T> printFirst(item: T) where T : List<String>, T : Comparable<T> {
println(item[0])
}
fun main() {
val list = listOf("apple", "banana")
printFirst(list)
}where clause:fun <T> compareItems(a: T, b: T) where T : Comparable {
return a.compareTo(b) > 0
}T : Comparable is incomplete; Comparable requires a type parameter.T : Comparable<T> to specify T can be compared to itself.T which must be both a Collection of Int and implement Iterable. Which is the correct way to declare the function with a where clause?T : Collection<Int>, T : Iterable<Int>.Pass the test and this pattern moves unknown