Kotlin泛型实战:从基础到高阶
Kotlin 泛型基础泛型允许在定义类、接口或函数时使用类型参数从而提高代码的复用性和类型安全性。Kotlin 的泛型语法与 Java 类似但提供了更灵活的特性。class BoxT(val value: T) fun main() { val intBox Box(1) // 类型推断为 BoxInt val stringBox Box(Hi) // 类型推断为 BoxString }泛型函数泛型不仅限于类函数也可以使用泛型。泛型函数的类型参数放在函数名之前。fun T singletonList(item: T): ListT { return listOf(item) } fun main() { val list singletonList(Kotlin) // 类型推断为 ListString }泛型约束通过where或:可以对泛型类型参数添加约束限制其必须满足某些条件。fun T : ComparableT maxOf(a: T, b: T): T { return if (a b) a else b } fun main() { println(maxOf(10, 20)) // 输出: 20 }型变协变与逆变Kotlin 通过out和in关键字支持型变分别表示协变和逆变。协变 (out) 允许子类型关系传递给泛型类型interface Producerout T { fun produce(): T } fun main() { val stringProducer: ProducerString object : ProducerString { override fun produce(): String Hello } val anyProducer: ProducerAny stringProducer // 合法因为 String 是 Any 的子类 }逆变 (in) 允许父类型关系传递给泛型类型interface Consumerin T { fun consume(item: T) } fun main() { val anyConsumer: ConsumerAny object : ConsumerAny { override fun consume(item: Any) { println(item) } } val stringConsumer: ConsumerString anyConsumer // 合法因为 Any 是 String 的父类 }星号投影 (*)当泛型类型参数的具体类型不重要时可以使用星号投影 (*)类似于 Java 的?。fun printList(list: List*) { list.forEach { println(it) } } fun main() { printList(listOf(1, 2, 3)) // 输出: 1 2 3 printList(listOf(A, B, C)) // 输出: A B C }泛型与 reified 类型参数在 Kotlin 中通过reified关键字可以在内联函数中访问泛型的具体类型。inline fun reified T checkType(item: Any) { if (item is T) { println(Item is of type ${T::class.simpleName}) } else { println(Item is not of type ${T::class.simpleName}) } } fun main() { checkTypeString(Kotlin) // 输出: Item is of type String checkTypeInt(Kotlin) // 输出: Item is not of type Int }泛型与扩展函数泛型可以与扩展函数结合为特定类型的类添加功能。fun T ListT.customFilter(predicate: (T) - Boolean): ListT { return this.filter(predicate) } fun main() { val numbers listOf(1, 2, 3, 4, 5) val evenNumbers numbers.customFilter { it % 2 0 } println(evenNumbers) // 输出: [2, 4] }泛型与委托Kotlin 的委托属性可以与泛型结合实现类型安全的属性委托。class GenericDelegateT(private var value: T) { operator fun getValue(thisRef: Any?, property: KProperty*): T value operator fun setValue(thisRef: Any?, property: KProperty*, newValue: T) { value newValue } } fun main() { var text by GenericDelegate(Initial) println(text) // 输出: Initial text Updated println(text) // 输出: Updated }泛型与集合Kotlin 的标准库集合大量使用泛型提供了类型安全的集合操作。fun K, V mergeMaps(map1: MapK, V, map2: MapK, V): MapK, V { return map1 map2 } fun main() { val map1 mapOf(A to 1, B to 2) val map2 mapOf(C to 3, D to 4) val merged mergeMaps(map1, map2) println(merged) // 输出: {A1, B2, C3, D4} }
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2414979.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!