[Day 15] 看不懂 exposed DAO?談談 object 和 companion object

昨天我們看了 exposed DAO 的寫法,有的地方是 Kotlin 獨有,可能看起來有一點吃力

今天我們來談談 object 和 companion object

object

首先我們看這段

object Cities: IntIdTable() {
    val name = varchar("name", 50)
}

這裡的 object 對應一般設計模式的 singleton,也就是從第一次宣告開始,每次宣告都是同一物件的一個模式。

exposed 這裡使用一個 singleton 來處理針對資料表的處理。

companion object

另外,我們看到這段

class City(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<City>(Cities)
    var name by Cities.name
}

這裡的 City 是我們存取資料的 DAO 類別,這個類別的所有物件裡面當然要包含所有 Cities 的 parameter。

這時我們使用的是 Kotlin 的 companion object。

官方對 companion object 的說明如下:

If you need a function or a property to be tied to a class rather than to instances of it (similar to @staticmethod in Python), you can declare it inside a companion object:

這正好是我們這裡的需求:我們希望可以有一個物件,綁定整個類別,而不只是單一物件。

以上簡單的介紹 DAO 用到專屬 Kotlin 的語法。