• Kotlin 使用泛型


    Kotlin 中,我们可以使用泛型(Generics)来编写具有通用性的代码,以增强代码的可重用性和类型安全性。通过使用泛型,我们可以在不指定具体类型的情况下编写适用于多种类型的函数和类。

    以下是 Kotlin 中使用泛型的几种方式:

    1. 函数泛型:

       fun  genericFunction(value: T) {
           // 在函数体中可以使用类型 T 进行操作
           println("Value: $value")
       }
       
       // 调用函数时,可以自动推断泛型类型
       genericFunction("Hello") // Value: Hello
       genericFunction(123) // Value: 123
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    2. 类泛型:

       class GenericClass(private val value: T) {
           fun getValue(): T {
               return value
           }
       }
       
       // 创建泛型类的实例时,可以指定具体的类型参数
       val stringClass = GenericClass("Hello")
       println(stringClass.getValue()) // Hello
       
       // 也可以自动推断类型参数
       val intClass = GenericClass(123)
       println(intClass.getValue()) // 123
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
    3. 约束泛型类型
      我们可以使用约束(Bounds)来限制泛型类型的范围,例如指定泛型类型必须是某个特定接口的实现或继承自某个类:

       interface Printable {
           fun print()
       }
       
       class MyClass(private val value: T) {
           fun doPrint() {
               value.print()
           }
       }
       
       class StringPrinter : Printable {
           override fun print() {
               println("Printing a string")
           }
       }
       
       val printer = MyClass(StringPrinter())
       printer.doPrint() // Printing a string
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18

      在上述示例中,MyClass 需要一个泛型类型 T,而 T 必须是实现 Printable 接口的类。因此,我们可以创建 MyClass 的实例,并传递一个实现了 Printable 接口的类 StringPrinter。
      通过使用泛型,我们可以编写更加通用和灵活的代码,减少代码重复,同时保持类型安全性。泛型在集合类(如 List、Set、Map)以及许多标准库函数中得到广泛应用,可以提供更好的编程体验和代码质量。

  • 相关阅读:
    《Linux设备驱动开发详解》之udev用户空间设备管理
    WebServer流程讲解(注册模块)
    JavaEE——网络编程(TCP流编程)
    【研0需要知道的那些事01】如何判断期刊是否为核心期刊?
    Kafka一个节点挂掉,导致服务不可消费
    数据结构练习&插入数据
    8.12 对抗攻击和防御
    重测序基因组:Pi核酸多样性计算
    计算机毕业设计课题题目列表信息
    LabVIEW应用程序在Windows版本之间的字体变化
  • 原文地址:https://blog.csdn.net/wolf0706/article/details/133355188