Allow name to be used as default value for enum primary constructor parameters


#1

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"
}

#2

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

#3

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.


#4

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
}

#5

Yes, that works, but I still prefer to have language support for name as a default parameter value as it would reduce boilerplate.


#6

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.