Allow accessing "this" before calling super for const members

I have an enum class, which I want to initialize in few ways.
Therefore I have a few constructors.
I use the name of the enum item - this.name. That’s a const.

But Kotlin prevents me from using it:

constructor(…) : this(…, MetricDetail(metricName = this.name.toLowerCase().replace(’_’, ‘.’)))

This fails because it accesses “this”.
I think for this case it is no problem to allow access, since “this.name” is a const which comes with the class.

I have tried other ways, like an init() function like I do in Java, but then, Kotlin things the val’s are not initialized.
So in the end, I need to copy the init code to all constructors.

Thanks for considering.

1 Like

I’m not sure this will be something that can be done easily. This will probably require something like KT-14652(constexp keyword) to be implemented first. At that point it shouldn’t be to hard to make someEnum.name into a compile time constant. That said it doesn’t look like this is going to be implemented soon. I haven’t heard anything about this when they talked about kotlin 1.4 so my guess is that best case scenario they start on this sometime between 1.4 and 1.5 and probably not before the compiler rework is done, so maybe only after 1.5.


I’m currius, what does RFE stand for, I haven’t heard seen this abbreviation before. Maybe it’s something obvious but I’m not a native speaker :wink:

The name of the enum can be identified as a compile time constant by the compiler, so I think it should not require any extra keywords… In principle, it’s the same as checking if something can be assigned to “const val”. But true, I don’t know Kotlin internals.


RFE = Request For Enhancement. Maybe it’s too old abbrev to be used nowadays :slight_smile:
http://acronymsandslang.com/definition/973458/RFE-meaning.html

I didn’t mean to imply that this would be the only possible way to implement this. I agree that since this is a constant known at compile time so the compiler could have some special case for this value. The problem with that is that you would add lot’s of special cases for a number of different values, I’m sure enum.name isn’t the only constant out there.
A better approach IMO would be to have a unifed system for stuff like this and constexp is a way that could solve this problem and is also required for functions like trimMargin so it will need to be implemented at some point.

Actually it can’t right now. const val foo = SomeEnum.Bar.name does not compile. It is treated like any other member property. Yes, this property will always return a constant that is technically known at compile time, but right now the compiler doesn’t know that.

this property will always return a constant that is technically known at compile time, but right now the compiler doesn’t know that.

That is exactly the matter of this feature request - to make the compiler know that.