https://kotlinlang.org logo
#android
Title
# android
v

vimlesh yadav

01/20/2023, 7:47 AM
Hello guys, I don't know how to use the Koltin delegation, can anyone help me understand it and what are the use cases for it?
If you have specific questions, ask in #getting-started
v

vimlesh yadav

01/20/2023, 8:32 AM
Ok Thanks
j

John Matthews

01/30/2023, 2:32 PM
This explanation for me helped better. I just wish they would tell me why use this over Inheritance≥. I always struggle with the why part in Kotlin. It seems they like to invent things but the why and when I would use this is a mystery over proven patterns.
c

CLOVIS

01/30/2023, 3:34 PM
@John Matthews let's imagine you have :
Copy code
interface Game {
    val name: String

    /** `true` if [move] is legal. */
    fun canPlay(move: Move): Boolean

    fun play(move: Move)

    // some other methods…
}

class Game1 : Game {
    override val name get() = "Game 1"
    …
}

class Game2 : Game {
    override val name get() = "Game 2"
    …
}
What if you wanted to create variants of games where you can only play 3 moves? With regular inheritance you'd have to create a new class for each
Game
subclass! With composition (implemented using delegation):
Copy code
// Takes a Game implementation as parameter, and adds the maximum move count rule to it
class LimitedGame(private val game: Game, private val maxCount: Int) : Game by game {
    private var currentCount = 0

    override val canPlay(move: Move): Boolean {
        if (currentCount >= maxCount)
            return false
        currentCount++
        return game.canPlay(move)
    }

    // no need to implement the other methods, they are all delegated to the original game instance
}
over proven patterns
Composition is a proven pattern. For example, it's item 16 in Effective Java, which doesn't even have composition at the language feature. It's also mentioned in the original Design Patterns book from 1994
(btw I recommend reading that item of Effective Java, it gives other examples of when to use it and describes in more details why it's useful)
j

John Matthews

01/30/2023, 3:38 PM
I forgot about the link I read. But thanks this makes it better to understand the when and why. https://en.wikipedia.org/wiki/Delegation_pattern
8 Views