Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read string into Enumeration without throwing an exception?

I have some data as .csv. It gets input by hand into Excel, and I have to load it into a Scala program.

Most of the fields of a single record are a freetext string or a number, but a few ones come from a prespecified short list of possible strings. I created enumerations for this type of information, like

object ScaleType extends Enumeration {
    val unknown = Value("unknown")
    val nominal = Value("nominal")
    val ordinal = Value("ordinal")
    val interval = Value("interval")
    val ratio = Value("ratio")
}

I read the csv into an Iterator[Array[String]], and for each line, I create new instance of a scala class, setting its properties from the information in the line. Assume that in the csv, it is line(8) which tells us the scale type we used. So, line is an Array[String], line(8) is a string, and its content should be one of the values listed in the enumeration.

As the data is input by hand, it contains errors. I used an if statement to find out if line(8) is completely empty, but I can't figure out how to see if the string I am getting is a scale type at all.

val scale = if(line(8).length > 0)
            {
                ScaleType.withName(line(8))
            }
        else ScaleType.unknown

What I'd like to happen: If somebody has entered the scale type "rtnl", I want the above to set the val scale to ScaleType.unknown and log the problem (something like print("scale reading error on line " + lineNumber will be enough). Instead, an exception gets thrown and I don't know how to check for a problem before the exception happens.

like image 596
rumtscho Avatar asked Jan 24 '26 02:01

rumtscho


1 Answers

You could use ValueSet.find:

val scale = ScaleType.values.find(_.toString == line(8)).getOrElse(ScaleType.unknown)

if this is too inefficient you could create a map:

val lookup = ScaleType.values.map(v => (v.toString, v)).toMap
val scale = lookup.get(line(8)).getOrElse(ScaleType.unknown)
like image 135
Lee Avatar answered Jan 25 '26 17:01

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!