I'm trying to extract values from a tokenised String and create an (optional) case class instance from it.
The String takes the form of:
val text = "name=John&surname=Smith"
I have a Person class which will accept both values:
case class Person(name: String, surname: String)
I have some code which does the conversion:
def findKeyValue(values: Array[String])(prefix: String): Option[String] =
values.find(_.startsWith(prefix)).map(_.substring(prefix.length))
val fields: Array[String] = text.split("&")
val personOp = for {
name <- findKeyValue(fields)("name=")
surname <- findKeyValue(fields)("surname=")
} yield Person(name, surname)
While this yields the answer I need I was wondering:
- Is there a more efficient way to do this?
- Is there a more Functional Programming-centric way to do this?
Some constraints:
The order of the name and surname fields in the text can change. The following is also valid:
val text = "surname=Smith&name=John"There could be other fields which need to be ignored:
val text = "surname=Smith&name=John&age=25"The solution needs to cater for when the text supplied is malformed or has none of the required fields.
The solution can't use reflection or macros.