2

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

svkaka
  • 3,942
  • 2
  • 31
  • 55

1 Answers1

2

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
}
shkschneider
  • 17,833
  • 13
  • 59
  • 112
  • isn't name final? Also, I am working on a library and I think it's still recommended to use enum annotation type instead of enums, so I would like to stick with that – svkaka Mar 07 '19 at 09:29
  • I made it `val` so it's final yes, but that's up to you. Now if you don't want to use enum.. – shkschneider Mar 07 '19 at 09:36
  • I mean IDE shows me an error "name in Enum is final and can't be overriden" – svkaka Mar 07 '19 at 09:38
  • before adding override it was "name hides member of supertype and needs 'override' modifier" – svkaka Mar 07 '19 at 09:39
  • Yeah ok, I was making that code out of my head, I fixed it. `name` was indeed reserved ;) – shkschneider Mar 07 '19 at 09:43