Kotlin 泛型(Generics)


Kotlin 泛型(Generics)

泛型就是將資料型別參數化,讓你在定義類別介面、類別、方法時不用先決定資料型別,例如 List<T> 中間的 T 指的就是泛型。在下面例子中,我想要有個 Box 能裝進各種 Animal。

首先有個 interface Animal

interface Animal {
    val name: String
}

我現在 implement 下來寫了兩個品種貓跟狗

class Cat : Animal {
    override val name: String
        get() = "Cat"

    fun cute(): String {
        return "裝可愛"
    }
}

class Dog : Animal {
    override val name: String
        get() = "Dog"

    fun swing(): String {
        return "搖尾巴"
    }
}

我需要個盒子讓上面的貓貓狗狗進去盒子

class Box<T : Animal>(val animal: T)

此時我想把裡面的可愛小動物拿出來我可以這麼使用

val dog = Dog()
val box = Box(dog)
print(box.animal.swing())

也可以這麼使用喵喵

val cat = Cat()
val box = Box(cat)
print(box.animal.cute())

回頭再看

class Box<T : Animal>(val animal: T)

public class Box 定義了類別名稱以及他是個 class

<T extends Animal> 定義了 T 型態必須是繼承或是擴充自 Animal

其實我們這麼寫也可以public class Box<Animal> 只要是擴充或是繼承自 Animal 都可以

這是因為 Kotlin 有很方便的型別推斷 因此特別的暴力

-

泛型在 Kotlin 中也可用在 mothod 定義上

我們先以 Java 為例

// java
<T extends Animal> String getName(T animal) {
    return animal.getName();
}

Kotlin 是這麼表示

//kotlin
fun <T: Animal>getName(animal: T):String {
    return animal.name
}

但 Kotlin 中如果方法只有一個 return 還有個很好用的寫法

//kotlin
inline fun <T: Animal>getName(animal: T): String = animal.name

WRITTEN BY
Aki

熱愛寫code的開發者,專注於 Android 手機 Native App 開發,對於 IOS 也有涉略。閒暇之餘也學習 JavaScript 等前端框架