Kotlin - 将枚举值赋给变量而不使用.value

时间:2017-01-12 13:29:14

标签: enums kotlin

现在是什么样的:

class Trial {
    companion object{
        @JvmStatic fun main(args: Array<String>){
            val message = Message.ALREADY_REGISTERED.value
            println(message);
        }
    }
}

enum class Message constructor(val value: String){
    ALREADY_REGISTERED("You've already been registered")
}

输出:You've already been registered。但我想知道,有没有办法只分配val message = Message.ALREADY_REGISTERED并立即获得价值而无需使用.value

尝试此操作时(使用我想要的代码)

class Trial {
    companion object{
        @JvmStatic fun main(args: Array<String>){
            val message = Message.ALREADY_REGISTERED
            println(message);
        }
    }
}

enum class Message constructor(val value: String){
    ALREADY_REGISTERED("You've already been registered")
}

输出ALREADY_REGISTERED

那么我可以将枚举值的值设为默认值而不是它的名称吗?

1 个答案:

答案 0 :(得分:5)

您需要覆盖enum class的<{3}}:

enum class Message(val value: String) {
    ALREADY_REGISTERED("You've already been registered");

    override fun toString() = value
}

如果您希望能够将您的枚举类视为CharSequence(如StringBuilder和其他String类似的话),也可以使用toString():< / p>

enum class Message(val value: String) : CharSequence by value {
    ALREADY_REGISTERED("You've already been registered");

    override fun toString() = value
}

然后您可以像使用其他任何CharSequence一样使用它。 e.g:

buildString {
    append("Message received: ")
    appendln(Message.ALREADY_REGISTERED)
    appendln()
    appendln("Don't forget to do your laundry.")
}