is it possible to implement an interface for an ex...
# getting-started
l
is it possible to implement an interface for an existing class (like traits in rust) ?
j
No, but you can write an adapter for it
l
what is an adapter ?
j
It's just a way to name a "wrapper" class that you write specifically to wrap an existing class and make it implement a given interface:
Copy code
class Dog {
    fun walk() {
        println("I'm a walking dog")
    }
}

interface Animal {
    fun move()
}

class DogToAnimalAdapter(private val dog: Dog): Animal {
    override fun move() {
        dog.walk()
    }
}

fun Dog.asAnimal(): Animal = DogToAnimalAdapter(this)
Still quite manual. You can also make this a bit shorter by implementing the interface anonymously:
Copy code
fun Dog.asAnimal(): Animal = object : Animal {
    override fun move() {
        walk()
    }
}
In this case you don't declare a particular adapter class. It's shorter but it has its shortcomings: you may want to think about equality of those instances etc.