is it possible to implement an interface for an existing class (like traits in rust) ?
j
Joffrey
02/01/2022, 2:38 PM
No, but you can write an adapter for it
l
LastExceed
02/01/2022, 2:38 PM
what is an adapter ?
j
Joffrey
02/01/2022, 2:41 PM
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)
Joffrey
02/01/2022, 2:43 PM
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.