【问题标题】:Understanding the syntax of this enum statement了解此枚举语句的语法
【发布时间】:2019-01-08 10:09:38
【问题描述】:

我遇到了以下用于枚举的 Kotlin 代码:

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()),
    ;
}

但是,当我查看有关枚举的 Kotlin 文档时,我没有看到任何显示这种语法的内容。行:

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

我不明白这三个参数是如何使用的。此外,枚举类 Section 显示了 3 个似乎没有使用的构造函数参数。

关于枚举的官方文档位于:

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

【问题讨论】:

  • Section 构造函数有 3 个参数,并且 GUIDE() 调用传递了 3 个匹配类型的参数,这应该会响起。您链接到的文档的第二个示例中使用了相同的语法,它只是一个略微简化的版本
  • 那么这算是匿名类吗?
  • 不,我不知道你是怎么得出这个结论的
  • 这在 Java 中也是可能的。这里有一个例子 - stackoverflow.com/a/8811869/816416

标签: kotlin


【解决方案1】:

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

每个枚举常量都是一个对象

所以GUIDESection 类的一个实例,意味着一个对象初始化为

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

你可以得到初始化GUIDE的值,像这样:

val guidePosition = Section.GUIDE.position
val guideTextKey = Section.GUIDE.textKey
val guideFragment = Section.GUIDE.fragment

【讨论】:

  • “GUIDE 是 Section 类的实例”是最重要的要点。这不完全是文档的说法。所以你的解释更好。谢谢。
【解决方案2】:

通常你的枚举是这样的

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

没有任何参数

但在您的示例中,枚举的基本构造函数也具有设置为属性的参数

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

在构造函数中使用关键字 val 设置为类的属性

那么它有

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())

所以对于GUIDE 0 -> 位置,R.string.main_pager_guide -> textKey 和 QotGuideFragment -> 片段

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-07
    • 2023-01-30
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多