Домой United States USA — software Kotlin Pearls: Multiple Inheritance

Kotlin Pearls: Multiple Inheritance

265
0
ПОДЕЛИТЬСЯ

Let’s focus on a Kotlin feature that can sometimes give you a little bit of trouble, the »by» keyword, and how to handle multiple inheritances.
Let’s be friends:
Comment (0)
Join the DZone community and get the full member experience.
This is the fifth article in a series about little known features of Kotlin. You can find the previous posts here, and here.
Let’s talk today about what used to be my least favorite Kotlin feature: the bykeyword. It was my least favorite because I saw it useful for a very limited number of use cases only and it was an unnecessary complication.
I discovered later that, on the contrary, it works very well together with other Kotlin features and is really beneficial if you know how to use it wisely.
First things first: the by keyword has two different uses in Kotlin:
This post is only about the first use. I will post in the future about the property delegation, which also has some surprises in store.
Let’s have a first look at the most straightforward case.
Remember that only interfaces can be delegated — it won’t work with an open abstract class.
So, we define an interface with two implementations: one is supposed to be the real one and the other for testing purposes.
So far, so good. Now, let’s say we need another class that implements ApiClient but adding new functionalities.
It’s a perfect case for the by operator. It specifies that we want to implement an interface using an existing instance. It can use an instance created on the fly or an object:
You can test that it works, but exactly what is happening here?
To see it, we can inspect the Kotlin bytecode (on IntelliJ Tools| Kotlin| Show Kotlin Bytecode) produced by the class DoSomething.

Continue reading...