In kotlin is there a way to give an interface to a class you don't own? I'm trying to reimplement a class from another library and want a shared contract between mine and that one as an intermediary until I'm finished.
c
Colton Idle
01/23/2021, 7:02 AM
i dont believe so. The best thing you can do i think is to just wrap that class and have that wrapper implement your interface.
scenario
(Duck) Class I don't own
(Animal) Interface I created
(Cat) Class I own that impls Animal
Create a Duck2 class that implements the Animal, but is actually just a Duck class.
Then if you have List<Animal> you could add Cats and Duck2s, to your hearts content.
I think theres a name for that kind of pattern.. but im also new to kotlin so you can wait to hear from others too.
open class A {
fun method1() {
println("A: method1")
}
fun method2() {
println("A: method2")
}
}
interface B {
fun method2()
}
class C: A(), B
fun main() {
val b: B = C()
b.method2()
}
With this pattern you can even specify
method2
as from B
r
Rob Elliot
01/23/2021, 12:58 PM
It’s a shame kotlin won’t allow this:
Copy code
class CannotBeChanged {
fun someMethod() {}
}
interface NewInterface {
fun someMethod()
}
class MyClass(delegate: CannotBeChanged) : NewInterface by delegate
In principal it could observe that
CannotBeChanged
meets all the requirements to implement
NewInterface
and so could be used as the delegate to do so in
MyClass
.
👍 2
n
Nir
01/23/2021, 1:44 PM
Yeah would be really nice for Kotlin delegation to be extended to handle more cases
a
Andrew
01/23/2021, 4:33 PM
I went with a wrapper for the class but might change to extending the class + interface. Originally I did not to that because many methods contain the class itself but I can make the interface take a T parameter