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.
fun <T : SomeType> functionName(param: T) { // code using param }
fun <T : Number> printDouble(value: T) { println(value.toDouble() * 2) }
fun <T> copyItems(source: List<T>, destination: MutableList<T>) where T : Any { for (item in source) { destination.add(item) } }
class Box<T : Comparable<T>>(val value: T) { fun isGreaterThan(other: T): Boolean { return value > other } }
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")) }
<T : Number> mean in Kotlin generics?<T : Number> means T is limited to types that inherit from Number.<T : Interface> to specify T must implement that interface.fun <T : Comparable<T>> .... Options B and D use Java syntax, and A uses a where clause but with incorrect syntax.fun <T : Number> printDouble(value: T) {
println(value.toDouble() * 2)
}
fun main() {
printDouble(5)
printDouble(3.5)
}fun <T : Comparable> compareValues(a: T, b: T): T {
return if (a > b) a else b
}fun <T : Number> sumList(numbers: List<T>): Double {
return numbers.sumOf { it.toDouble() }
}Pass the test and this pattern moves unknown