是否可以向Kotlin中的现有类添加接口? [英] Is it possible to add an interface to an existing class in Kotlin?
问题描述
有时候,创建一个已经由现有第三方代码(例如,从库中)实现的接口很有用.例如,我们可以想象选择一个String
类方法的子集并声明一个GenericString
.然后,我们可能会定义实现这些方法的其他GenericString
,而不是String
类的其他方法.唯一的问题是String
类不会从GenericString
类继承.是否可以向Kotlin中的现有类添加接口,还是我必须创建实现该接口的String
子类?
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?
推荐答案
否,不幸的是,不支持扩展类型".在Kotlin论坛上对此进行了讨论(此处),但该语言中没有类似的东西.
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.
如果您想投票,请使用 KEEP .
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
}
,然后改用它.
这篇关于是否可以向Kotlin中的现有类添加接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!