Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - assign value of enum to variable without .value

Tags:

enums

kotlin

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?

like image 550
Ivar Reukers Avatar asked Feb 06 '23 08:02

Ivar Reukers


1 Answers

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.")
}
like image 99
mfulton26 Avatar answered Feb 10 '23 08:02

mfulton26