Dart Mixins from Android/Kotlin Developer Perspective

It’s a kind of multiple-inheritance magic✨

Rahman Adianto
Bootcampers
2 min readOct 2, 2022

--

Photo by Dmitry Demidov at Pixels

Multi-platform mobile app development is not a new “wizard” for me. Back then in 2017 when react-native raised and flutter was introduced, I was not a big fan of this approach. Year by year, the data have spoken, and the growth of multi-platform app development is crazy fast. It changed my mind, I decided to give multi-platform app development (flutter) another shoot.

https://insights.stackoverflow.com/trends?tags=flutter%2Creact-native

When I started to learn Dart, the concept of mixins caught my eye. At first, I found this concept somewhat confusing, until I realized that we can achieve the same with kotlin. So, in this article, I’ll give you Dart mixins from the Android/Kotlin developer perspective.

What are mixins?

Mixins are a way of reusing a class’s code in multiple class hierarchies. So it’s just an Object Oriented Programming inheritance? No. It’s look-like “multiple inheritances”. So kotlin and dart support multiple inheritances? It depends. If we want to achieve true multiple inheritances like C++ that enable us to do class A : B, C where class B and class C , the answer is no. If we only want methods/properties from B and C available from A , the answer is yes. That is why the Dart team defines mixins as a way of reusing a class’s code rather than multiple inheritances support.

Why do we need mixins?

One usecase that come to my mind when do we need mixins is ability composition. Let’s say we have animal classification and have 3 ability categorizations, Walker, Swimmer, and Flyer. Given a Salmon, it would be easy to classify as a Swimmer, but how about Duck? The problem is Duck is a Swimmer as well as a Walker.

First, below code would be the one possible solution in kotlin.

In above example we use kotlin interface and implement it using by delegation. With that, we can easily compose Salmon, Duck or other Animal.

Second, let’s see below code to see how we achieve the same with Dart.

Conclusion

We saw that mixins are a powerful tool to reuse or compose code. Further more, it’s easy to understand from kotlin world perspective.

If you have any questions, feel free to post them 👇.

Any feedback is welcome ❤️.

--

--

Rahman Adianto
Bootcampers

Software Engineer — Android | I write about mobile app development | Connect with me on LinkedIn https://www.linkedin.com/in/rhmndnt/