上限

最常见的类型约束就是上限,这个的意义和Java中的extends关键字等价。

fun <T : Comparable<T>> sort(list: List<T>) {
    // ...
}

冒号后面特定类型就是上限:只有是Comparable<T>的子类才可以取代T。

sort(listOf(1, 2, 3)) // OK. Int is a subtype of Comparable<Int>
sort(listOf(HashMap<Int, String>())) // Error: HashMap<Int, String> is not a subtype of

默认的上限(如果未指定的话)就是Any?。尖括号中只能指定一个上限。如果需要多个上限,那么我们需要使用where语句:

fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T>
    where T : Comparable,
          T : Cloneable {
    return list.filter { it > threshold }.map { it.clone() }
}

results matching ""

    No results matching ""