0

In scala I have an algebraic type I would like to work with:

case class Person(name: String, age: Int, weight: Float)

A library I do not control is providing me values via an enumeration of String values:

Enumeration(("name", "Bob"), ("age", "32"), ("weight", "45.64"))
Enumeration(("age", "23"), ("weight", "20.0"), ("name", "Alice"))

What's the most "scala-ish" way to get the annoying (name,value) string pairs into my case class?

I've only thought of the obvious iterative CRUD method:

def toClass(e: Enumeration[(String,String)]): Person = {
  var name: String = _
  ...
  for(pair <- e) pair._1 match {
    "name" => name = pair._2
  }

  Person(name, ...)
}
Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125

1 Answers1

2

Just convert it to the Map:

def toClass(e : Enumeration[(String,String)]) : Person = {
    val raw = e.values.toMap
    Person(raw("name"), raw("age").toInt, raw("weight").toFloat)
}

There is also macro-based universal solution

P.S. I assume your Enumeration is some custom type, as scala's Enumeration doesn't take type parameters and can't hold list of tuples (actually it can, but it's not cannonical way to use it). So e.values should return list of tuples.

Community
  • 1
  • 1
dk14
  • 22,206
  • 4
  • 51
  • 88