Kotlin为枚举类值方法定义接口 [英] Kotlin define interface for enum class values method
本文介绍了Kotlin为枚举类值方法定义接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我定义了一个枚举类,那么说:
if I define an enum class, let's say:
enum class MyEnum { }
我可以做以下事情,因为枚举类都具有values
方法:
I can do the following as enum class all have a values
method:
val values = MyEnum.values()
现在,我希望我的枚举实现一个接口并可以访问values()方法:
Now I want my enum to implement an interface and have access to the values() method:
enum class MyEnum : EnumInterface { }
interface EnumInterface {
fun values() : Array<T>
fun doStuff() {
this.values()
}
}
这不会编译,我确定如何键入values方法.是否可以定义这样的接口?谢谢!
This doesn't compile and I'm sure how to type the values method. Is it possible to define such interface? Thanks!
推荐答案
您真的很接近正确的答案.您需要定义通用接口,枚举应使用枚举的类扩展它,如下所示:
You were really close to correct answer. You need to define generic interface and you enum should extend it typed with enum's class like this:
enum class MyEnum : EnumInterface<MyEnum> {
A,B,C;
override fun valuesInternal() = MyEnum.values()
}
interface EnumInterface<T> {
fun valuesInternal():Array<T>
fun doStuff() {
this.valuesInternal()
}
}
这篇关于Kotlin为枚举类值方法定义接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文