Kotlin中的枚举注释类型

时间:2019-03-07 09:10:34

标签: android kotlin

在Java中,我可以这样定义枚举注释类型(来自here

// Constants
public static final String WINTER = "Winter";
public static final String SPRING = "Spring";
public static final String SUMMER = "Summer";
public static final String FALL = "Fall";

// Declare the @ StringDef for these constants:
@StringDef({WINTER, SPRING, SUMMER, FALL})
@Retention(RetentionPolicy.SOURCE)
public @interface Season {}

此代码的Kotlin版本是什么?

使用此工具时出现问题(使用IDE直接转换)

// Constants
private const val WINTER = "Winter"
private const val SPRING = "Spring"
private const val SUMMER = "Summer"
private const val FALL = "Fall"

// Declare the @ StringDef for these constants:
@StringDef(WINTER, SPRING, SUMMER, FALL)
@Retention(AnnotationRetention.SOURCE)
annotation class Season

因为我无法访问例如Season.WINTER

1 个答案:

答案 0 :(得分:0)

在Kotlin中,最好使用enum class。在Kotlin中转换@IntDef@StringDef的用法时,我遇到很多问题。

enum class Season constructor(val value: String) {
  WINTER("Winter"),
  SPRING("Spring"),
  SUMMER("Summer"),
  FALL("Fall");

  override fun toString(): String = value
}