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

假装没事ソ 提交于 2020-04-10 08:06:46

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!