0

I came across the following Kotlin code for an enum:

enum class Section(val position: Int, val textKey: Int, val fragment: Fragment) {

    GUIDE(0, R.string.main_pager_guide, QotGuideFragment()),
    LEARN(1, R.string.main_pager_learn, QotLearnFragment()),
    ME(2, R.string.main_pager_me, QotToBeVisionFragment()),
    PREPARE(3, R.string.main_pager_prepare, QotPrepareFragment()),
    ;
}

However, when I review the Kotlin docs on enums, I don't see anything in it that shows this kind of syntax. The line:

GUIDE(0, R.string.main_pager_guide, QotGuideFragment())

I don't understand how these 3 parameters are used. Also, the enum class Section shows 3 constructor parameters that don't appear to be used.

The official docs on enum are at:

https://kotlinlang.org/docs/reference/enum-classes.html

Johann
  • 27,536
  • 39
  • 165
  • 279
  • the Section constructor has 3 params, and the GUIDE() call passes 3 params of matching types, that should ring a bell. The same syntax is used in the 2nd example of the docs you link to, it's just a slighlty simplified version – Tim Jan 08 '19 at 10:14
  • So is this considered an anonymous class? – Johann Jan 08 '19 at 10:31
  • no, I'm not sure how you came to that conclusion – Tim Jan 08 '19 at 10:44
  • **And this is possible in Java too**. An example here - https://stackoverflow.com/a/8811869/816416 – Vishnu Haridas Jan 08 '19 at 19:31

2 Answers2

1

From https://kotlinlang.org/docs/reference/enum-classes.html:

Each enum constant is an object

so GUIDE is an instance of Section class, meaning an object initialized as

GUIDE(0, R.string.main_pager_guide, QotGuideFragment())

You can get the values that initialized GUIDE, like this:

val guidePosition = Section.GUIDE.position
val guideTextKey = Section.GUIDE.textKey
val guideFragment = Section.GUIDE.fragment
forpas
  • 160,666
  • 10
  • 38
  • 76
  • "GUIDE is an instance of Section class" is the most important take-away. That isn't exactly how the docs word it. So your explanation is better. Thanks. – Johann Jan 08 '19 at 10:40
0

usually your enums will be like that

enum class Section() {
    GUIDE,
    LEARN,
    ME,
    PREPARE
}

without any parameters

but in your example the base constructor of the enum has parameters that are set as properties also

enum class Section(**val** position: Int, **val** textKey: Int, **val** fragment: Fragment) 

with the keyword val in the constructor you set as property of the class

then it has

GUIDE(0, R.string.main_pager_guide, QotGuideFragment()),
LEARN(1, R.string.main_pager_learn, QotLearnFragment()),
ME(2, R.string.main_pager_me, QotToBeVisionFragment()),
PREPARE(3, R.string.main_pager_prepare, QotPrepareFragment())

so for GUIDE 0 -> position, R.string.main_pager_guide -> textKey and QotGuideFragment -> fragment

gmetax
  • 3,853
  • 2
  • 31
  • 45