class Hello<T>(val value: T) val box = Box<Int>(1) val box1 = Box(2)
fun <T> foo(item: T): List<T> {
// do something
}
val list = foo<Int>(1)
fun <T> T.toString2(): String {
// 扩展函数
}
fun <K, V>put(key: K, value: V) {
// 多个泛型参数
}
// Java
interface Source<T> {
T nextT();
}
void demo(Source<String> strs) {
Source<Object> objects = strs; // !!! 在 Java 中禁止这样的操作
// ...
}
abstract class Source<out T> {
abstract fun nextT(): T
}
fun demo(strs: Source<String>) {
val objects: Source<Any> = strs // 这是 OK 的, 因为 T 是一个 out 类型参数
// ...
}
abstract class Comparable<in T> {
abstract fun compareTo(other: T): Int
}
fun demo(x: Comparable<Number>) {
x.compareTo(1.0) // 1.0 类型为 Double, 是 Number 的子类型
// 因此, 我们可以将 x 赋值给 Comparable<Double> 类型的变量
val y: Comparable<Double> = x // OK!
}
class Array<T>(val size: Int) {
fun get(index: Int): T { /* ... */ }
fun set(index: Int, value: T) { /* ... */ }
}
fun copy(from: Array<Any>, to: Array<Any>) {
assert(from.size == to.size)
for (i in from.indices)
to[i] = from[i]
}
val ints: Array<Int> = arrayOf(1, 2, 3)
val any = Array<Any>(3)
copy(ints, any) // 错误: 期待的参数类型是 (Array<Any>, Array<Any>)
fun copy(from: Array<out Any>, to: Array<Any>) {
// ...
}
fun fill(dest: Array<in String>, value: String) {
// ...
}
fun <T : Comparable<T>> sort(list: List<T>) {
// ...
}
sort(listOf(1, 2, 3)) // 正确: Int 是 Comparable<Int> 的子类型
sort(listOf(HashMap<Int, String>())) // 错误: HashMap<Int, String> 不是
// Comparable<HashMap<Int, String>> 的子类型
inline fun <reified T>runtimeType(): Unit {
println("My type parameter is " + T::class.qualifiedName)
}
inline fun <reified T>List<Any>.collect(): List<T> {
return this.filter { it is T }.map { it as T }
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有