Home > Java > javaTutorial > Implementing Mixins (or Traits) in Kotlin Using Delegation

Implementing Mixins (or Traits) in Kotlin Using Delegation

Mary-Kate Olsen
Release: 2024-10-18 20:11:03
Original
1061 people have browsed it

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()

        // ...
    }
}
Copy after login
Copy after login
Copy after login

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")
    }
}
Copy after login
Copy after login
Copy after login

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:

class MyClass {
    private val mixin = Counter()

    fun myFunction() {
        mixin.increment()

        // ...
    }
}
Copy after login
Copy after login
Copy after login

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 {
    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")
    }
}
Copy after login
Copy after login
Copy after login

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.
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...
    }
}
Copy after login
Copy after login

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.

class MyClass {
    private val mixin = Counter()

    fun myFunction() {
        mixin.increment()

        // ...
    }
}
Copy after login
Copy after login
Copy after login

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 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")
    }
}
Copy after login
Copy after login
Copy after login

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 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...
    }
}
Copy after login
Copy after login

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 ↩

The above is the detailed content of Implementing Mixins (or Traits) in Kotlin Using Delegation. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template