Skip to content

Instantly share code, notes, and snippets.

@gustavofranke
Created March 21, 2018 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavofranke/9a06087b52f332a1d100db195bbb4a3c to your computer and use it in GitHub Desktop.
Save gustavofranke/9a06087b52f332a1d100db195bbb4a3c to your computer and use it in GitHub Desktop.
test("pipe delimited to jvm obj") {
case class Person(fullName: String, age: Int, address: String, hs: String)
object Parser {
def splitByPipe(s: String): Array[String] = s.split('|')
def init(key: String, ps: Map[String, String]): String = ps.getOrElse(key, "")
def bind(headers: List[String], pipeDelimited: String): Map[String, String] = headers
.zip(splitByPipe(pipeDelimited).toList)
.toMap
def newPerson(msg: String): Person = {
val personHeader = List("full_name", "age", "address")
val keysAndValues: Map[String, String] = bind(personHeader, msg)
Person(
fullName = init("full_name", keysAndValues),
age = init("age", keysAndValues).toInt,
address = init("address", keysAndValues),
hs = "hardcoded stuff")
}
}
val pipe = "Miles Davis|36|123 Main St, Ny"
val person = Parser.newPerson(pipe)
println(person) // Person(Miles Davis,36,123 Main St, Ny,hardcoded stuff)
println(person.fullName) // Miles Davis
println(person.age) // 36
println(person.address) //123 Main St, Ny
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment