Please allow the name
property to be used as the default value for enum primary constructor parameters. e.g.,:
enum class Example (
val text: String = name
) {
A, // text == "A"
B("BB") // text == "BB"
}
Please allow the name
property to be used as the default value for enum primary constructor parameters. e.g.,:
enum class Example (
val text: String = name
) {
A, // text == "A"
B("BB") // text == "BB"
}
You could do something like this:
fun main(args: Array<String>) {
Example.values().forEach { println(it.text) }
}
//sampleStart
enum class Example {
A, // text == "A"
B("BB"); // text == "BB"
val text: String
constructor(text: String) {
this.text = text
}
constructor() {
this.text = this.name
}
}
//sampleEnd
My example was just a trivial example. My real use case enum has many String
properties that should default to name
, but that are overridden on a per property & enum constant basis. So writing constructor overloads would get tedious fast.
enum class Example(a: String? = null, b: String? = null){
A, // text == "A"
B("BB"), // text == "BB"
C(b = "foo");
val a: String = a ?: this.name
val b: String = b ?: this.name
}
Yes, that works, but I still prefer to have language support for name as a default parameter value as it would reduce boilerplate.
By how much would the boilerplate be reduced? Will it save 10,000 lines in a million line code base?
You should ask the questions above before suggesting language features. A language feature is quite expensive: compiler, documentation, IDE integration, tooling, etc. If the amount of boilerplate that can be removed is in the dozens of lines for a large code base, I think it is not worth the effort.
This would be useful for class delegation
enum class MyEnum: MyInterface by name {
…
}
Also wanted to say that this would be a nice feature, not strictly necessary but would help to keep enums concise, personally I am using the pattern below as a workaround. It’s not much but it adds up when it’s used in multiple places
enum class Example (
text: String? = null
) {
A, // text == "A"
B("BB"); // text == "BB"
val text: String = text ?: name
}