」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用委託在 Kotlin 中實現 Mixins(或 Traits)

使用委託在 Kotlin 中實現 Mixins(或 Traits)

發佈於2024-11-15
瀏覽:501

Implementing Mixins (or Traits) in Kotlin Using Delegation

(Read this article in french on my website)

In object-oriented programming, a Mixin is a way to add one or more predefined and autonomous functionalities to a class. Some languages provide this capability directly, while others require more effort and compromise to code Mixins. In this article, I explain an implementation of Mixins in Kotlin using delegation.

  • Objective
    • Definition of the "Mixins" Pattern
    • Characteristics and Constraints
  • Implementation
    • Naive Approach by Composition
    • Use of Inheritance
    • Delegation to Contain the Mixin’s State
    • Final Implementation
  • Limitations
  • Examples
    • Auditable
    • Observable
    • Entity / Identity
  • Conclusion

Objective

Definition of the "Mixins" Pattern

The mixin pattern is not as precisely defined as other design patterns such as Singleton or Proxy. Depending on the context, there may be slight differences in what the term means.

This pattern can also be close to the "Traits" present in other languages (e.g., Rust), but similarly, the term "Trait" does not necessarily mean the same thing depending on the language used1.

That said, here is a definition from Wikipedia:

In object-oriented programming, a mixin (or mix-in) is a class that contains methods used by other classes without needing to be the parent class of those other classes. The way these other classes access the mixin’s methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited."

You can also find definitions in various articles on the subject of mixin-based programming (2, 3, 4). These definitions also bring this notion of class extension without the parent-child relationship (or is-a) provided by classical inheritance. They further link with multiple inheritance, which is not possible in Kotlin (nor in Java) but is presented as one of the interests of using mixins.

Characteristics and Constraints

An implementation of the pattern that closely matches these definitions must meet the following constraints:

  • We can add several mixins to a class. We’re in an object-oriented context, and if this constraint weren’t met, the pattern would have little interest compared to other design possibilities like inheritance.
  • Mixin functionality can be used from outside the class. Similarly, if we disregard this constraint, the pattern will bring nothing we couldn’t achieve with simple composition.
  • Adding a mixin to a class does not force us to add attributes and methods in the class definition. Without this constraint, the mixin could no longer be seen as a "black box" functionality. We could not only rely on the mixin’s interface contract to add it to a class but would have to understand its functioning (e.g., via documentation). I want to be able to use a mixin as I use a class or a function.
  • A mixin can have a state. Some mixins may need to store data for their functionality.
  • Mixins can be used as types. For example, I can have a function that takes any object as a parameter as long as it uses a given mixin.

Implementation

Naive Approach by Composition

The most trivial way to add functionalities to a class is to use another class as an attribute. The mixin’s functionalities are then accessible by calling methods of this attribute.

class MyClass {
    private val mixin = Counter()

    fun myFunction() {
        mixin.increment()

        // ...
    }
}

This method doesn’t provide any information to Kotlin’s type system. For example, it’s impossible to have a list of objects using Counter. Taking an object of type Counter as a parameter has no interest as this type represents only the mixin and thus an object probably useless to the rest of the application.

Another problem with this implementation is that the mixin’s functionalities aren’t accessible from outside the class without modifying this class or making the mixin public.

Use of Inheritance

For mixins to also define a type usable in the application, we will need to inherit from an abstract class or implement an interface.

Using an abstract class to define a mixin is out of the question, as it would not allow us to use multiple mixins on a single class (it is impossible to inherit from multiple classes in Kotlin).

A mixin will thus be created with an interface.

interface Counter {
    var count: Int
    fun increment() {
        println("Mixin does its job")
    }
    fun get(): Int = count
}

class MyClass: Counter {
    override var count: Int = 0 // We are forced to add the mixin's state to the class using it

    fun hello() {
        println("Class does something")
    }
}

This approach is more satisfactory than the previous one for several reasons:

  • The class using the mixin doesn’t need to implement the mixin’s behavior thanks to default methods
  • A class can use multiple mixins as Kotlin allows a class to implement multiple interfaces.
  • Each mixin creates a type that can be used to manipulate objects based on the mixins included by their class.

However, there remains a significant limitation to this implementation: mixins can’t contain state. Indeed, while interfaces in Kotlin can define properties, they can’t initialize them directly. Every class using the mixin must thus define all properties necessary for the mixin’s operation. This doesn’t respect the constraint that we don’t want the use of a mixin to force us to add properties or methods to the class using it.

We will thus need to find a solution for mixins to have state while keeping the interface as the only way to have both a type and the ability to use multiple mixins.

Delegation to Contain the Mixin’s State

This solution is slightly more complex to define a mixin; however, it has no impact on the class using it. The trick is to associate each mixin with an object to contain the state the mixin might need. We will use this object by associating it with Kotlin’s delegation feature to create this object for each use of the mixin.

Here’s the basic solution that nevertheless meets all the constraints:

interface Counter {
    fun increment()
    fun get(): Int
}

class CounterHolder: Counter {
    var count: Int = 0
    override fun increment() {
        count  
    }
    override fun get(): Int = count
}

class MyClass: Counter by CounterHolder() {
    fun hello() {
        increment()
        // The rest of the method...
    }
}

Final Implementation

We can further improve the implementation: the CounterHolder class is an implementation detail, and it would be interesting not to need to know its name.

To achieve this, we’ll use a companion object on the mixin interface and the "Factory Method" pattern to create the object containing the mixin’s state. We’ll also use a bit of Kotlin black magic so we don’t need to know this method’s name:

interface Counter {
    // The functions and properties defined here constitute the mixin's "interface contract." This can be used by the class using the mixin or from outside of it.
    fun increment()
    fun get(): Int

    companion object {
        private class MixinStateHolder : Counter {
            // The mixin's state can be defined here, and it is private if not also defined in the interface
            var count: Int = 0

            override fun increment() {
                count  
            }
            override fun get(): Int = count
        }

        // Using the invoke operator in a companion object makes it appear as if the interface had a constructor. Normally I discourage this kind of black magic, but here it seems one of the rare justified cases. If you don't like it, rename this function using a standard name common to all mixins like `init` or `create`.
        operator fun invoke(): Counter {
            return MixinStateHolder()
        } 
    }
}

class MyClass: Counter by Counter() {
    fun myFunction() {
        this.increment()
        // The rest of the method...
    }
}

Limitations

This implementation of mixins is not perfect (none could be perfect without being supported at the language level, in my opinion). In particular, it presents the following drawbacks:

  • All mixin methods must be public. Some mixins contain methods intended to be used by the class using the mixin and others that make more sense if called from outside. Since the mixin defines its methods on an interface, it is impossible to force the compiler to verify these constraints. We must then rely on documentation or static code analysis tools.
  • Mixin methods don’t have access to the instance of the class using the mixin. At the time of the delegation declaration, the instance is not initialized, and we can’t pass it to the mixin.
    class MyClass: MyMixin by MyMixin(this) {} // Compilation error: `this` is not defined in this context

If you use this inside the mixin, you refer to the Holder class instance.

Examples

To improve understanding of the pattern I propose in this article, here are some realistic examples of mixins.

Auditable

This mixin allows a class to "record" actions performed on an instance of that class. The mixin provides another method to retrieve the latest events.

import java.time.Instant

data class TimestampedEvent(
    val timestamp: Instant,
    val event: String
)

interface Auditable {
    fun auditEvent(event: String)
    fun getLatestEvents(n: Int): List

    companion object {
        private class Holder : Auditable {
            private val events = mutableListOf()
            override fun auditEvent(event: String) {
                events.add(TimestampedEvent(Instant.now(), event))
            }
            override fun getLatestEvents(n: Int): List {
                return events.sortedByDescending(TimestampedEvent::timestamp).takeLast(n)
            }
        }

        operator fun invoke(): Auditable = Holder()
    }
}

class BankAccount: Auditable by Auditable() {
    private var balance = 0
    fun deposit(amount: Int) {
        auditEvent("deposit $amount")
        balance  = amount
    }

    fun withdraw(amount: Int) {
        auditEvent("withdraw $amount")
        balance -= amount 
    }

    fun getBalance() = balance
}

fun main() {
    val myAccount = BankAccount()

    // This function will call deposit and withdraw many times but we don't know exactly when and how
    giveToComplexSystem(myAccount)

    // We can query the balance of the account
    myAccount.getBalance()

    // Thanks to the mixin, we can also know the operations that have been performed on the account.
    myAccount.getLatestEvents(10)
}

Observable

The design pattern Observable can be easily implemented using a mixin. This way, observable classes no longer need to define the subscription and notification logic, nor maintain the list of observers themselves.

interface Observable {
    fun subscribe(observer: (T) -> Unit)
    fun notifyObservers(event: T)

    companion object {
        private class Holder : Observable {
            private val observers = mutableListOf Unit>()
            override fun subscribe(observer: (T) -> Unit) {
                observers.add(observer)
            }

            override fun notifyObservers(event: T) {
                observers.forEach { it(event) }
            }
        }

        operator fun  invoke(): Observable = Holder()
    }
}

sealed interface CatalogEvent
class PriceUpdated(val product: String, val price: Int): CatalogEvent

class Catalog(): Observable by Observable() {
    val products = mutableMapOf()

    fun updatePrice(product: String, price: Int) {
        products[product] = price
        notifyObservers(PriceUpdated(product, price))
    }
}

fun main() {
    val catalog = Catalog()

    catalog.subscribe { println(it) }

    catalog.updatePrice("lamp", 10)
}

There is a disadvantage in this specific case, however: the notifyObservers method is accessible from outside the Catalog class, even though we would probably prefer to keep it private. But all mixin methods must be public to be used from the class using the mixin (since we aren’t using inheritance but composition, even if the syntax simplified by Kotlin makes it look like inheritance).

Entity / Identity

If your project manages persistent business data and/or you practice, at least in part, DDD (Domain Driven Design), your application probably contains entities. An entity is a class with an identity, often implemented as a numeric ID or a UUID. This characteristic fits well with the use of a mixin, and here is an example.

interface Entity {
    val id: UUID

    // Overriding equals and hashCode in a mixin may not always be a good idea, but it seems interesting for the example.
    override fun equals(other: Any?): Boolean
    override fun hashCode(): Int
}

class IdentityHolder(
    override val id: UUID
): Entity {
    // Two entities are equal if their ids are equal.
    override fun equals(other: Any?): Boolean {
        if(other is Entity) {
            return this.id == other.id
        }

        return false
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }
}

class Customer(
    id: UUID,
    val firstName: String,
    val lastName: String,
) : Entity by IdentityHolder(id)

val id = UUID.randomUUID()
val c1 = Customer(id, "John", "Smith")
val c2 = Customer(id, "John", "Doe")

c1 == c2 // true

This example is a bit different: we see that nothing prevents us from naming the Holder class differently, and nothing prevents us from passing parameters during instantiation.

Conclusion

The mixin technique allows enriching classes by adding often transverse and reusable behaviors without having to modify these classes to accommodate these functionalities. Despite some limitations, mixins help facilitate code reuse and isolate certain functionalities common to several classes in the application.

Mixins are an interesting tool in the Kotlin developer’s toolkit, and I encourage you to explore this method in your own code, while being aware of the constraints and alternatives.


  1. Fun fact: Kotlin has a trait keyword, but it is deprecated and has been replaced by interface (see https://blog.jetbrains.com/kotlin/2015/05/kotlin-m12-is-out/#traits-are-now-interfaces) ↩

  2. Mixin Based Inheritance ↩

  3. Classes and Mixins ↩

  4. Object-Oriented Programming with Flavors ↩

版本聲明 本文轉載於:https://dev.to/zenika/implementing-mixins-or-traits-in-kotlin-using-delegation-3pkh?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-15
  • 顯示未知數量的卡片時如何防止 Flex 項目重疊?
    顯示未知數量的卡片時如何防止 Flex 項目重疊?
    重疊 Flex 項目問題水平顯示一組未知數量的撲克牌,如果它們超過一定寬度,可能會導致它們重疊。 Flex 框可以用於此目的,但控制大小和重疊可能很棘手。 解決方案此解決方案涉及設定特定的 CSS 屬性以實現所需的效果。細分如下:Container:.cards 容器使用 flexbox (disp...
    程式設計 發佈於2024-11-15
  • uint8_t 總是等於 unsigned char 嗎?
    uint8_t 總是等於 unsigned char 嗎?
    對uint8_t 和unsigned char 等價性的調查C 和C 領域中uint8_t 和unsigned char 之間的相互作用提出了有關它們的問題可能出現的分歧。特別是,當 CHAR_BIT 超過 8 時,就會出現問題,導致 uint8_t 無法封裝在 8 位元內。 定義 uint8_t ...
    程式設計 發佈於2024-11-15
  • 建立 Redis 克隆:深入研究內存資料存儲
    建立 Redis 克隆:深入研究內存資料存儲
    在資料儲存解決方案領域,Redis 作為強大的記憶體鍵值儲存脫穎而出。憑藉其高性能和多功能性,它已成為許多開發人員的首選。在這篇文章中,我將引導您從頭開始建立 Redis 克隆的過程,分享見解、挑戰以及我在過程中所做的設計選擇。 項目概況 該專案的目標是複製 Redis 的基本功能...
    程式設計 發佈於2024-11-15
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-15
  • 如何在 Python 中使用 Lambda 函數
    如何在 Python 中使用 Lambda 函數
    Python 中的 Lambda 函数是动态创建小型匿名函数的强大方法。这些函数通常用于简短的操作,其中不需要完整函数定义的开销。 传统函数是使用 def 关键字定义的,而 Lambda 函数是使用 lambda 关键字定义的,并且直接集成到代码行中。特别是,它们经常用作内置函数的参数。它们使开发人...
    程式設計 發佈於2024-11-15
  • Java 8 中 Stream.map() 和 Stream.flatMap() 之間的主要差異是什麼?
    Java 8 中 Stream.map() 和 Stream.flatMap() 之間的主要差異是什麼?
    Java 8 中的Stream.map() 與Stream.flatMap()Stream.map() 和Stream.flatMap()是Java 8 中兩種常用的方法,它們會對值流執行類似的轉換。然而,它們在處理和傳回值的方式上有根本的差異。 Stream.map()接受一個 Function
    程式設計 發佈於2024-11-15
  • 如何更改預設 Python 版本:為什麼我的終端機仍然使用 Python 2?
    如何更改預設 Python 版本:為什麼我的終端機仍然使用 Python 2?
    如何更改預設Python 版本:超越相容性問題您安裝了Python 3.2,儘管運行了Update Shell Profile 命令,終端終端終端機仍存在顯示Python 2.6.1。這種差異可能會令人困惑,所以讓我們探討一下如何更改預設的 Python 版本。 歷史背景:向後相容性和多個版本過去,...
    程式設計 發佈於2024-11-15
  • 負文字縮排是從無序列表中刪除縮排的唯一方法嗎?
    負文字縮排是從無序列表中刪除縮排的唯一方法嗎?
    從無序列表中刪除縮排:負文字縮排是唯一的解決方案嗎? 問題出現了:如何消除無序列表中的所有縮排無序列表元素 (ul),儘管嘗試將邊距、填充和文字縮排設為 0。雖然將文字縮排設定為負值似乎可以竅門,這是唯一的方法嗎? 答案在於將列表樣式和左填充設為空。透過執行以下程式碼,即可達到想要的效果:ul { ...
    程式設計 發佈於2024-11-15
  • 使用 Pandas“apply”函數將函數應用於多列時如何修復錯誤?
    使用 Pandas“apply”函數將函數應用於多列時如何修復錯誤?
    多列的Pandas“apply”函數故障排除嘗試使用“apply”將函數應用於Pandas 資料框中的多列時' 函數時,如果列名未包含在字串中或函數定義中出現語法錯誤,使用者可能會遇到錯誤訊息。 要解決未定義名稱的問題,請確保指定列名在單引號或雙引號內。例如,不要使用 'row[a]...
    程式設計 發佈於2024-11-15
  • 為什麼應該避免在函數簽名中使用“throw”?
    為什麼應該避免在函數簽名中使用“throw”?
    函數簽名中“Throw”的危險雖然在函數簽名中加入“throw”關鍵字可能很誘人明確聲明潛在的例外情況,強烈建議不要這樣做。儘管其目的看似簡單,但有幾個技術原因導致這種方法被認為是一個糟糕的選擇。 編譯器限制編譯器無法強制執行會產生一個重大問題函式簽章中宣告的例外規格。因此,編譯器無法驗證函數是否確...
    程式設計 發佈於2024-11-15
  • 如何在 MySQL 中將行轉置為列:超越 GROUP_CONCAT 的限制?
    如何在 MySQL 中將行轉置為列:超越 GROUP_CONCAT 的限制?
    在MySQL 中將行轉置為列:探索替代技術在MySQL 中將行轉置為列:探索替代技術問題: 我們如何在MySQL 查詢中有效地將行轉置為列? 答案: MySQL 本質上並沒有提供直接的機制來轉置整個結果 套。但是,我們可以探索替代方法來實現所需的轉換。 儘管 GROUP_CONCAT 在將行轉換為單...
    程式設計 發佈於2024-11-15
  • 為什麼我的 Font Awesome 圖示沒有渲染?
    為什麼我的 Font Awesome 圖示沒有渲染?
    Font Awesome 圖示不渲染:原因與解決方案Font Awesome 圖示是增強網頁視覺吸引力的熱門選擇。然而,儘管包含了所需的 CSS 和 HTML,但有些使用者還是遇到了圖示無法正確呈現的問題。本文探討了此問題的潛在原因並提供了解決方案。 一個常見問題是 CDN 連結不正確。確保Font...
    程式設計 發佈於2024-11-15
  • std 命名空間內的專業化有哪些限制和允許?
    std 命名空間內的專業化有哪些限制和允許?
    std 命名空間中的專業化:限制和允許儘管能夠為std 命名空間添加明確專業化,但某些模板有明確的禁止。了解這些限制對於確保使用 std 命名空間特化的程式碼的有效性至關重要。 特化禁止的模板numeric_limits: 不允許非算術標準類型(例如, complex).shared_ptr: 必須...
    程式設計 發佈於2024-11-15
  • CSS 圖靈完備嗎?
    CSS 圖靈完備嗎?
    CSS 是圖靈完備的。這意味著,如果您將 CSS 視為適當的 HTML 檔案和一種使用者互動類型,則可以執行任意不可計算的功能。此外,Webkit CSS 可以對規則 110 進行編碼以證明圖靈完備性。這意味著 CSS 是一種快速、獨立於平台、圖靈完整的語言。
    程式設計 發佈於2024-11-15

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3