现在是什么样的:
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
。
那么我可以将枚举值的值设为默认值而不是它的名称吗?
答案 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.")
}