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?
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
CodePudding user response:
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{
//...
}
}
}