Created
March 21, 2018 11:57
-
-
Save gustavofranke/9a06087b52f332a1d100db195bbb4a3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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