Last active
August 29, 2015 14:25
-
-
Save joecwu/c87eda0b3e3c0f663f44 to your computer and use it in GitHub Desktop.
Blog Scala - unapply http://blog.joecwu.com/2015/07/scala-unapply-extraction-method.html
This file contains hidden or 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
case class GetArticleRequest(id:String,country:String,language:String) | |
def parseRequest(queryStr:String) = { | |
// parse arguments | |
val args = queryStr.split('&') map { str => | |
val pair = str.split('=') | |
(pair(0) -> pair(1)) | |
} toMap | |
// get 'id','country','language' and gen GetArticleRequest object | |
val resp = for{ | |
id <- args.get("id") | |
country <- args.get("country") | |
language <- args.get("language") | |
}yield(GetArticleRequest(id,country,language)) | |
resp | |
} | |
object TestApp { | |
def run { | |
val queryString = "id=abc&country=TW&language=zh" | |
// Extract value | |
val request = parseRequest(queryString).getOrElse(thrown Exception("invalid request")) | |
println(s"id:[${request.id}], country:[${request.country}], language:[${request.language}]") | |
// Pattern match | |
val request2 = parseRequest(queryString).getOrElse(thrown Exception("invalid request")) | |
request2 match { | |
case GetArticleRequest(id,country,language) => println(s"id:[$id], country:[$country], language:[$language]") | |
} | |
} | |
} |
This file contains hidden or 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
object GetArticleRequest { | |
def unapply(queryStr:String): Option[(String, String, String)] = { | |
// parse arguments | |
val args = queryStr.split('&') map { str => | |
val pair = str.split('=') | |
(pair(0) -> pair(1)) | |
} toMap | |
// get 'id','country','language' | |
val resp = for{ | |
id <- args.get("id") | |
country <- args.get("country") | |
language <- args.get("language") | |
}yield((id,country,language)) | |
resp | |
} | |
} | |
object TestApp { | |
def run { | |
// Extract value directly | |
val GetArticleRequest(id,country,language) = "id=abc&country=TW&language=zh" | |
println(s"id:[$id], country:[$country], language:[$language]") | |
// Pattern match | |
"id=abc&country=TW&language=zh" match { | |
case GetArticleRequest(id,country,language) => println(s"id:[$id], country:[$country], language:[$language]") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment