What it's like now:
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")
}
This outputs: You've already been registered
. But I was wondering, is there a way to just assign val message = Message.ALREADY_REGISTERED
and have the value immediately without having to use .value
?
When trying this (with the code I want)
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")
}
it outputs ALREADY_REGISTERED
.
So can I make the value of the enum return default instead of it's name?
You need to override toString()
for your enum class
:
enum class Message(val value: String) {
ALREADY_REGISTERED("You've already been registered");
override fun toString() = value
}
You can also use class delegation if you want to be able to treat your enum class as a CharSequence
(like StringBuilder
and other String
-like classes):
enum class Message(val value: String) : CharSequence by value {
ALREADY_REGISTERED("You've already been registered");
override fun toString() = value
}
Then you can use it just like any other CharSequence
. e.g.:
buildString {
append("Message received: ")
appendln(Message.ALREADY_REGISTERED)
appendln()
appendln("Don't forget to do your laundry.")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With