How to implement abstract function in Enum constants

1.8k views Asked by At

What I'm trying to achieve is a simple pattern that I'm using in Java and should be do-able in Kotlin according to the documentation. I just want to declare an enum class with a couple of constant definitions that implement the same abstract functions.

My problem is that I cannot manage to make my code compile. I always get the same error:

modifier abstract not allowed here

Here is the code:

enum class Program {
    HOME {
        override fun readableName(context: Context): String {
            return context.getString(R.string.program_home)
        }
    },
    WEEKEND {
        override fun readableName(context: Context): String {
            return context.getString(R.string.program_weekend)
        }
    },
    SHOPPING {
        override fun readableName(context: Context): String {
            return context.getString(R.string.program_shopping)
        }
    };

    abstract fun readableName(context: Context): String
}

I have even tried with the sample code from the documentation and yet even this does not compile.

Could anyone have an idea about this odd issue? Btw I'm currently using Kotlin 1.0.6.

2

There are 2 answers

0
Stephen Vinouze On BEST ANSWER

Alright... so I found out where the issue was and it was not what I expected to be. @Kirill Rakhman was right, there was nothing wrong with the enum code. I had an issue with kapt that was unable for some reason to generate my project annotations. More specifically I was using - what I missed as experimental - the newly available gradle kapt plugin documented here.

I rolled back to the previous kapt settings by replacing

apply plugin: 'kotlin-kapt'

by

kapt {
    generateStubs = true
}

And it worked! Not sure why the compilation failed while declaring my enum though.

Thanks a lot for those who took time to look into it and if you have any idea why the experimental kapt plugin was not behaving as expected feel free to comment this answer, I would gladly want to know what happened :)

0
Anton  Malmygin On

I just tried your code and it's compiled normally with Kotlin plugin 1.0.6-release-Studio2.2-1

Maybe you can just try to update AndroidStudio/Kotlin plugin ?