问题
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?
回答1:
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.
What you could do, although it is not really the same, is have an interface for this and have an extension method returning an implementation 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.
来源:https://stackoverflow.com/questions/48861009/is-it-possible-to-add-an-interface-to-an-existing-class-in-kotlin