search
HomeJavajavaTutorialImplementing Mixins (or Traits) in Kotlin Using Delegation

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:

class MyClass {
    private val mixin = Counter()

    fun myFunction() {
        mixin.increment()

        // ...
    }
}

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")
    }
}

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...
    }
}

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

        // ...
    }
}

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")
    }
}

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...
    }
}

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!

Statement
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.