let's say I want map enum to and from my own strin...
# getting-started
m
let's say I want map enum to and from my own strings, so I just
override fun toString()
, and now I would like make
constructor(type: String)
that will create enum from appropriate string, anyone have idea how to accomplish such thing?
r
You can't use a constructor, but you could define a companion function for it:
Copy code
enum class Thing(val string: String) {
    A("a"), B("b"), C("c");

    override fun toString() = string

    companion object {
        private val values = values().associateBy { it.string }
        fun of(string: String) = values[string]
    }
}
and call it like so
Copy code
val a = Thing.of("a")
(Note that
a
will be
Thing?
. If you want
Thing
, you can either use
getValue
in
of
, or handle the null case at the call site.)
m
ohh nice! thank you ❤️! I will handle null checks on my own 😉
r
Also, I'd recommend accessing the string property and not relying on
.toString()
. It's generally considered bad form.
The toString method is widely implemented. It provides a simple, convenient mechanism for debugging classes during development. It's also widely used for logging, and for passing informative error messages to Exception constructors and assertions. When used in these informal ways, the exact format of toString is not part of the contract of the method, and callers should not rely on the exact format of the returned String.
http://www.javapractices.com/topic/TopicAction.do?Id=55
m
you are right, I already get rid of it since I saw it's no needed