Michał Kalinowski
10/17/2019, 3:36 PMoverride 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?Ruckus
10/17/2019, 3:50 PMenum 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
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.)Michał Kalinowski
10/17/2019, 4:00 PMRuckus
10/17/2019, 7:01 PM.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
Michał Kalinowski
10/18/2019, 7:22 AM