现在是什么样的:
class Trial { companion object{ @JvmStatic fun main(args: Array){ 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){ val message = Message.ALREADY_REGISTERED println(message); } } } enum class Message constructor(val value: String){ ALREADY_REGISTERED("You've already been registered") }
它输出ALREADY_REGISTERED
。
那么我可以将枚举返回的值设为默认值而不是其名称吗?
您需要toString()
为您覆盖enum class
:
enum class Message(val value: String) { ALREADY_REGISTERED("You've already been registered"); override fun toString() = value }
如果希望能够将枚举类视为(类似类和其他类似类),则也可以使用类委托:CharSequence
StringBuilder
String
enum class Message(val value: String) : CharSequence by value { ALREADY_REGISTERED("You've already been registered"); override fun toString() = value }
然后您可以像使用其他任何东西一样使用它CharSequence
。例如:
buildString { append("Message received: ") appendln(Message.ALREADY_REGISTERED) appendln() appendln("Don't forget to do your laundry.") }