class Box<T>(val value: T) {
fun <U> map(f: (T) -> U): Box<U> = Box(f(value))
}
// Generic function with a type bound
fun <T : Comparable<T>> max(list: List<T>): T {
var best = list[0]
for (item in list) if (item > best) best = item
return best
}
// Multiple bounds via `where`
fun <T> copyIfNotNull(src: T?, dst: T)
where T : Cloneable, T : java.io.Serializable {
/* ... */
}
fun main() {
val intBox: Box<Int> = Box(42)
val strBox: Box<String> = intBox.map { it.toString() }
println(strBox.value) // "42"
println(max(listOf(3, 1, 4, 1, 5, 9, 2))) // 9
println(max(listOf("apple", "banana", "cherry"))) // "cherry"
}
Create a free account and build your private vault. Share publicly whenever you want.