Home > OS >  Strings and sealed clases
Strings and sealed clases

Time:08-21

I need to obtain some string that match with another. For example, when my string is “Ne” I need to obtain “Neon”. I made this, but I think that this isn’t the best way. I think that is better use sealed class. Is there some way to match a string with an element from a sealed class?

fun getName(symbol: String): String{
        return when(symbol){
            "Ne" -> {"Neon"}
            "Ar" -> {"Argon"}
            "Kr" -> {"Krypton"}
            "Xe" -> {"Xenon"}
            "Rn" -> {"Radon"}
            "Br" -> {"Bromine"}
            else -> {""}
        }
    }

thanks!

CodePudding user response:

Sealed class would not better approach for this, because you may have to create a class within sealed class for every element. That is not recommended if you have many classes. Same thing would applicable to enums too. When condition will be fine for your case.

Alternatively, you can store it in hashmap as key value pairs. And get element by the Key.

var elements = hashMapOf(
    "Ne" to "Neon",
    "Ar" to "Argon",
    "Kr" to "Krypton",
    "Xe" to "Xenon",
    "Rn" to "Radon",
    "Br" to "Bromine"
)
val item = elements["as"]?:""

If element not present in map, ?: operator(elvis) would give empty string.

CodePudding user response:

A sealed class isn't going to really help you with this (you may have other reasons to do that though). You still need some way to convert the short name into the long name. There's two ways to do that:

1)Use a class with the short name and long name in it. Walk that list until you find a match. This is an O(n) operation.

2)Keep a map of short name->long name (or short name->class which has a long name). Then you just do a map lookup. This is an O(1) operation.

What you want is the second one. You can still use a sealed class in there if that gives you other advantages, but you want the map for the fast lookup.

  • Related