svkaka
svkaka

Reputation: 4032

Enumerated annotation type in Kotlin

In java I can define enumerated annotation type like this (from 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 {}

What is Kotlin version of this code?

I have a problem when using this (straight conversion using 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

as I cannot access e.g. Season.WINTER

Upvotes: 2

Views: 1587

Answers (1)

shkschneider
shkschneider

Reputation: 18253

In Kotlin you're better off using enum class. I had many problems converting @IntDef and @StringDef usages in Kotlin.

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

  override fun toString(): String = value
}

Upvotes: 2

Related Questions