In kotlin is there a way to give an interface to a...
# announcements
a
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
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.
j
It's called "the adapter pattern". https://en.m.wikipedia.org/wiki/Adapter_pattern
e
Yep I agree with comments above.
Copy code
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
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
Yeah would be really nice for Kotlin delegation to be extended to handle more cases
a
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
h
this is on many's wish list: https://youtrack.jetbrains.com/issue/KT-40900 and https://github.com/Kotlin/KEEP/pull/87 the last i heard was that it's being put aside for the moment, allowing development to focus on multiple receivers first. if you want the feature, you can upvote the KT issue.