Sometimes it is useful to create an interface that is already implemented by existing third-party code (ie. from a library). For example, we could imagine selecting a subset of the methods of the String
class and declaring a GenericString
. We might then define other GenericString
s that implement these methods, but not other methods of the String
class. The only problem would be that the String
class doesn't inherit from the GenericString
class. Is it possible to add an interface to an existing class in Kotlin or would I have to create a sub-class of String
that implements this interface?
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
A class in Kotlin can implement as many interfaces as they like but it can only extend from one abstract class.
Inheritance in Interfaces –Interfaces in Kotlin can also inherit other interfaces. When an interface extends another interface, it can add its own properties and methods, and the implementing type has to provide a definition for all the properties and methods in both the interfaces.
An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces.
No, unfortunately "extension types" are not supported. There was a discussion about this on the Kotlin forums (here), but there is nothing similar that is already in the language.
There is a KEEP for this if you would like to vote.
One possible workaround, although it is not fully equivalent, is to have an interface representing your desired behavior and create an extension method returning an implementation ("delegate") for every type you want to use:
fun String.toGenericString() = object : GenericString {
private val str = this@toGenericString
override val length get() = str.length
//...etc
}
and then use this instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With