Composition Over Inheritance In Kotlin Explained
Inheritance is bad… Everyone knows it, but why?
1. What is inheritance?
It’s a way for classes to ‘inherit’ all properties from another class. We usually say that the class we inherit is called a superclass, and the class that inherits properties is called a subclass.
In Kotlin, there’s Single Inheritance only, meaning there’ll always be a single subclass and a single superclass. In Kotlin, we can use it in two ways:
- With
open class
// With open classes
open class Cat {
fun meow() {
println("meow")
}
}class SpecificCat : Cat() {
fun specificFunction() {
println("specific")
}
}
fun main() {
val cat = Cat()
cat.meow() // meow
val specificCat = SpecificCat()
specificCat.meow() // meow
specificCat.specificFunction() // specific
}
2. With abstract class
abstract class Cat {
fun meow() {
println("meow")
}abstract fun specificFunction()
}
class SpecificCat : Cat() {
override fun specificFunction() {
println("specific")
}
}
fun main() {
// Creating Cat throws compilation error
// we can't create abstract classes
// val cat = Cat()
val specificCat = SpecificCat()
specificCat.meow() // meow
specificCat.specificFunction() // specific
}
Not that we would try to make SpecificCat
inherit from two classes, it’s impossible:
open class WalkingCat {
fun walk() {
println("walk")
}
}// Compilation error: Only one class may appear in a supertype list
class SpecificCat : Cat(), WalkingCat() {
override fun specificFunction() {
println("specific")
}
}
These are the main limitations:
- We can only inherit from a single class.
- We take everything from that class, even things we don’t need.
- It’s harder to read, especially when working with multiple levels of inheritance.
SpecificCat
could inherit fromCat
and thenSpecificWalkingCat
could inherit fromSpecificCat
while using methods defined inCat
class. It’s hard to navigate and understand that type of code.
2. What is Composition?
It’s a principle that classes should have ‘has a’ relationships. This way, we can divide and ‘compose’ the properties we class
should have. It’s done through Interface
s and classes that implement
them.
We could refactor the Inheritance example to use composition:
interface Mouth {
fun speak()
}class CatMouth : Mouth {
override fun speak() {
println("meow")
}
}
class SpecificCat {
private val mouth: Mouth = CatMouth()
fun meow() {
mouth.speak()
}
fun specificFunction() {
println("specific")
}
}
fun main() {
val specificCat = SpecificCat()
specificCat.meow() // meow
specificCat.specificFunction() // specific
}
Or, even better, by using Kotlin delegates, we’re able to add all the Mouth
functions to SpecificCat
:
class SpecificCat : Mouth by CatMouth() {
fun specificFunction() {
println("specific")
}
}fun main() {
val specificCat = SpecificCat()
// Now we use 'speak' because meow was removed
specificCat.speak() // meow
specificCat.specificFunction() // specific
}
The main benefits of using composition are:
- Reusability — you can reuse the implementation of an interface in multiple classes.
- ‘has a’ relationship — you can have multiple properties and compose code more readably.
- You control what is visible to the outside world and what is not!
- You can leverage Kotlin Delegates to add all properties from the implementing class without the drawbacks of inheritance.
If you’ve learned something new please clap and follow me for more!
Tags In
Related Posts
Leave a Reply Cancel reply
Categories
- ! Без рубрики (1)
- ++PU (1)
- 1 (1)
- 1w (1)
- 1win Brazil (1)
- 1win India (1)
- 1WIN Official In Russia (1)
- 1win Turkiye (1)
- 1xbet egypt (1)
- 2ankarafayansustasi.net_may (1)
- ankarafayansustasi.netsiteai apr (1)
- Artificial intelligence (1)
- Arts & Entertainment, Photography (1)
- belugasitesi_mAY (1)
- BH_TOPsitesi apr (1)
- BHsitesy_may (2)
- Blog (3)
- Bookkeeping (14)
- Bootcamp de programação (2)
- Bootcamp de programación (2)
- BT_TOPsitesi apr (1)
- casino (5)
- casinom-hub (1)
- casinom-hub.comsitesi apr (3)
- colombian mail order brides (1)
- Cryptocurrency exchange (2)
- Dinamobet_next (1)
- Disease & Illness, Colon Cancer (1)
- Dumanbet (1)
- Dumanbet_next (1)
- Finance, Insurance (1)
- FinTech (5)
- Forex Trading (11)
- Galabet (1)
- Health & Fitness, Fitness Equipment (1)
- Hitbet (1)
- Home & Family, Crafts (1)
- Home & Family, Gardening (1)
- Internet Business, Audio-Video Streaming (1)
- Internet Business, Ecommerce (1)
- Internet Business, Email Marketing (1)
- Internet Business, Internet Marketing (1)
- IT Вакансії (1)
- IT Образование (5)
- IT Освіта (1)
- latin women dating (1)
- mail order bride (1)
- Mars bahis (2)
- Matadorbet (1)
- minimiri.comsitesi apr (3)
- Mobile App Development (771)
- Mostbet Russia (1)
- New Post (1)
- News (12)
- PB_TOPsitesi apr (1)
- PBsitesi_may (1)
- Pusulabet (1)
- redmirepool.bizsitesi apr (2)
- redmirepoolsitesi_may (1)
- Reference & Education, College (1)
- Reference & Education, Sociology (1)
- Rokusitesi apr (1)
- Sober living (6)
- Society, Divorce (1)
- Software development (7)
- Superbetin (1)
- Tempobet_next (1)
- thelongeststride.comsitesi apr (1)
- tipobet-turkiyesitesi apr (1)
- Ultrabet (1)
- Uncategorized (1)
- Игра (2)
- казино (1)
- Криптовалюты (1)
- Новости Криптовалют (1)
- Финтех (7)
- Форекс Брокеры (9)
- Форекс обучение (2)