Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I launch a function in the base class of enum in kotlin in Android Studio?

In Code A, the ELevel is enum class, and the fun getLevel in the enum will return a subclass by the parameter soundValue.

The Code A can be compiled.

I think Code B is better, but in fact it can’t be compiled ,why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code A

data class MSoundDensity(  
    val avg: Double=0.0,
    val max: Double=0.0,
    val level: ELevel=ELevel.Whisper.getLevel(avg)    
)

enum class ELevel(val label:String){
   Whisper("Whisper"),
   Quiet("Quiet Library");

   fun getLevel(soundValue:Double):ELevel{
       var temp=Whisper
       val i=soundValue.toInt()

       if (i in 1..20){
           temp=Whisper
       }

       if (i in 21..40){
           temp=Quiet
       }

       return temp
   }

}

Code B

data class MSoundDensity(  
    val avg: Double=0.0,
    val max: Double=0.0,
    val level: ELevel=ELevel.getLevel(avg)  //It cause error when I use base class.    
)

//The same

>Solution :

Just like any other class, you have to put that function in a companion object if you want to call it like that instead of calling it on an instance of the class.

enum class ELevel(val label:String){
    Whisper("Whisper"),
    Quiet("Quiet Library");

    companion object {
        fun getLevel(soundValue:Double):ELevel{
           //...
        }
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading