首页 > 解决方案 > 接口中不允许使用属性初始化器

问题描述

我的 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();

}

标签: kotlininterface

解决方案


您可以使用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
    }
}

推荐阅读