Reputation: 9296
Trying to write a data class that will have two values one for the language code and display name. I need to change the display name based on the code. The values we get back from the feed are not the correct display names on all the values we use. So I need something that compares the languageDisplay with what is in the enum and then change languageDisplay if its in the enum. The code below is my start but stuck now:
data class ClosedCaptionOn(
val languageCode: String,
val languageDisplay: String
) : ClosedCaptionOptions(){
constructor(languageCode: String) : this(languageCode, ??? )
}
enum class ClosedCaptionLanguages(val code: String) {
eng("English"), zho("Chinese")
}
Upvotes: 0
Views: 823
Reputation: 93581
Your enum has a couple of naming issues. It looks like your value names are the codes, and the property is the display name, but you called the property code
. Also, it's weird to use a plural word for the enum class name, because the type you pass around represents a single object.
You can add a companion object function to provide a helper that looks up a display name or provides some default value when the code is not in the enum. You're right that valueOf
throws an exception if there's no corresponding enum value.
enum class ClosedCaptionLanguage(val displayName: String) {
eng("English"), zho("Chinese");
companion object {
fun displayNameFor(code: String, default: String = "Unsupported") =
runCatching { valueOf(code) }.getOrNull() ?: default
}
}
data class ClosedCaptionOn(
val languageCode: String,
val languageDisplay: String
) : ClosedCaptionOptions(){
constructor(languageCode: String) : this(languageCode, ClosedCaptionLanguage.displayNameFor(languageCode))
}
Upvotes: 2