接口中不允许使用属性初始值设定项

P1N*_*WIN 8 interface kotlin

我的 Java 项目有一个带有给定值的 ItemType 接口,该接口由某些类实现。如何在 Kotlin 上实现这个接口?

public interface ItemType {

int TYPE_OPTION = 2;
int TYPE_GRID = 3;
int TYPE_CAROUSEL = 4;
int TYPE_MUSIC = 5;
int TYPE_GUESS = 6;

int getItemType();

}
Run Code Online (Sandbox Code Playgroud)

gpu*_*nto 10

您可以使用companion object

interface ItemType {
    val itemType: Int

    companion object {
        const val TYPE_OPTION = 2
        const val TYPE_GRID = 3
        const val TYPE_CAROUSEL = 4
        const val TYPE_MUSIC = 5
        const val TYPE_GUESS = 6
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您能说明问题发生的原因以及解决方案的工作原理,那就更好了。 (4认同)