”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用委托在 Kotlin 中实现 Mixins(或 Traits)

使用委托在 Kotlin 中实现 Mixins(或 Traits)

发布于2024-11-15
浏览:202

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]删除
最新教程 更多>
  • 为什么我的 @font-face EOT 字体无法在 Internet Explorer 中通过 HTTPS 加载?
    为什么我的 @font-face EOT 字体无法在 Internet Explorer 中通过 HTTPS 加载?
    @font-face EOT 无法通过 HTTPS 加载:解决方案遇到 @font-face EOT 文件在 Internet 中无法通过 HTTPS 加载的问题在 Explorer 版本 7、8 和 9 中,用户发现无论 HTTPS 上包含的 HTML 页面的托管状态如何,问题仍然存在。经过实验,...
    编程 发布于2024-11-15
  • 为什么通过 Makefile 运行 Go 程序时出现“权限被拒绝”错误?
    为什么通过 Makefile 运行 Go 程序时出现“权限被拒绝”错误?
    权限被拒绝:调查“go run”和 Makefile 调用之间的差异通过 Makefile 运行 Go 程序时遇到权限被拒绝错误可能会令人困惑。此问题源于 GNU make 或其 gnulib 组件中的错误。根本原因在于系统 PATH 中存在一个名为“go”的目录,该目录位于实际 Go 可执行文件所...
    编程 发布于2024-11-15
  • 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
  • 可以使用 CSS 设计 SVG 背景图像吗?
    可以使用 CSS 设计 SVG 背景图像吗?
    您可以使用 CSS 设计 SVG 背景图像吗?作为 SVG 爱好者,您精通将 SVG 用作背景图像。然而,仍然存在一个持续存在的问题:您是否也可以在同一个文件中使用 CSS 设计 SVG 样式?遗憾的是,答案是不。用作背景图像的 SVG 被视为与 CSS 样式表隔离的单个实体。 CSS 文件中的样式...
    编程 发布于2024-11-15
  • 能否结合使用 LIKE 和 IN 来实现更强大的 SQL 查询?
    能否结合使用 LIKE 和 IN 来实现更强大的 SQL 查询?
    结合LIKE和IN进行高级SQL查询在SQL中,LIKE运算符经常用于模式匹配,而IN运算符允许我们将一个值与一系列特定值进行匹配。虽然这些运算符有不同的用途,但可以将它们组合起来创建更强大的查询。让我们考虑以下场景:您有一个表,其中有一列名为“company_id”,并且您想要选择其中包含该列的所...
    编程 发布于2024-11-15
  • 为什么PHP中逗号可以用于回显但不能用于返回?
    为什么PHP中逗号可以用于回显但不能用于返回?
    为什么用逗号回显有效,而用逗号返回却不起作用?在 PHP 中使用 echo 和 return 连接值时,有使用句号和逗号之间的细微差别。具体来说:Echo:允许以逗号分隔的多个表达式回显到输出。返回:只能返回一个单个表达式。使用句点句点 (.) 运算符将字符串或其他数据类型连接成单个字符串。例如:e...
    编程 发布于2024-11-15
  • 如何将 Django 数据库从 SQLite 迁移到 MySQL:分步指南
    如何将 Django 数据库从 SQLite 迁移到 MySQL:分步指南
    将 Django DB 从 SQLite 迁移到 MySQL将数据库从 SQLite 迁移到 MySQL 可能是一项艰巨的任务。由于可用的工具和脚本过多,因此很难确定最可靠和最直接的方法。一位经验丰富的 Django 开发人员建议了一个经受时间考验的解决方案。他们建议执行以下步骤:转储现有的 SQL...
    编程 发布于2024-11-15
  • 如何确保 JavaScript 中准确的整数验证:哪种方法最好?
    如何确保 JavaScript 中准确的整数验证:哪种方法最好?
    如何在 JavaScript 中验证整数输入无论是需要检查整数以确保数据一致性,还是需要向用户提示准确的错误消息,JavaScript 提供了多种验证方法整数输入。一种常见的方法是使用 parseInt() 函数。但是,如果您想要处理可能被解析为整数的字符串等场景,仅此方法可能不够。稳健的整数验证函...
    编程 发布于2024-11-15
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-11-15
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-11-15
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-11-15
  • 如何从现有模型自动生成 Sequelize 迁移?
    如何从现有模型自动生成 Sequelize 迁移?
    使用 Sequelize CLI 自动生成迁移为 Sequelize 模型创建迁移是数据库管理中的关键步骤。迁移使您能够跟踪数据库架构随时间的变化。虽然 Sequelize 提供了用于模型生成的 CLI 工具,但它还提供了从现有模型自动生成迁移的功能。要自动生成迁移,请按照以下步骤操作:安装 Seq...
    编程 发布于2024-11-15
  • 如何计算MySQL中两个日期之间的准确年龄差?
    如何计算MySQL中两个日期之间的准确年龄差?
    在 MySQL 中获取两个日期之间的年龄差在 MySQL 中,计算两个日期之间的年龄差可能具有挑战性,尤其是如果你想要它作为一个整数。通常,使用 DATEDIFF() 或除以 365 会导致浮点值或年份可能不准确。一种有效的方法是使用 TIMESTAMPDIFF() 和适当的日期单位:SELECT ...
    编程 发布于2024-11-15
  • 如何将变量中的凭证传递到 AWS 开发工具包版本 2 以进行 IAM 服务访问?
    如何将变量中的凭证传递到 AWS 开发工具包版本 2 以进行 IAM 服务访问?
    将凭证从变量传递到 AWS SDK 版本 2此查询呼应了之前有关使用来自变量的凭证的 AWS SDK 的问题。但是,在本例中,使用的是 SDK 版本 2,它消除了会话功能。要使用从变量获取的凭据建立新客户端以访问 IAM 服务,请考虑以下函数:func getIAMClient(ctx contex...
    编程 发布于2024-11-15
  • 使用 Python 通过 ODBC 或 JDBC 访问 IRIS 数据库
    使用 Python 通过 ODBC 或 JDBC 访问 IRIS 数据库
    字符串问题 我正在使用 Python 通过 JDBC(或 ODBC)访问 IRIS 数据库。 我想将数据提取到 pandas 数据框中来操作数据并从中创建图表。我在使用 JDBC 时遇到了字符串处理问题。这篇文章旨在帮助其他人遇到同样的问题。 或者,如果有更简单的方法来解决这个...
    编程 发布于2024-11-15

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3