Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add an interface to an existing class in Kotlin?

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 GenericStrings 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?

like image 560
Casebash Avatar asked Feb 19 '18 07:02

Casebash


People also ask

How do you add an interface to a class?

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.

How many interfaces can a class implement Kotlin?

A class in Kotlin can implement as many interfaces as they like but it can only extend from one abstract class.

Can an interface implement another interface Kotlin?

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.

Can a class extend another interface?

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.


1 Answers

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.

like image 56
Salem Avatar answered Oct 07 '22 21:10

Salem