Refactoring for a higher order function in Scala?
Learning Scala and trying to refactor the next two functions to remove duplicate logic. Should I create a higher order function or something else to avoid code duplication? There are several other similar methods with such duplicate code, with the difference that you call different domain methods.
A bit confused by refactoring. Using Scala version 2.10
def authenticate = Action(parse.json) { request =>
val json = request.body
val input = Json.fromJson[User](json)
input.asOpt match {
case Some(m: User) => Ok(Domain.authenticate(m)).as("application/json")
case None => Ok("bad input")
}
}
def addUser = Action(parse.json) { request =>
val json = request.body
val input = Json.fromJson[User](json)
input.asOpt match {
case Some(m: User) => Ok(Domain.addUser(m)).as("application/json")
case None => Ok("bad input")
}
}
+3
source to share
2 answers
I think you can do something like ( Unconfirmed ):
private def common[A](f:User=>A)(request:RequestHeader) = {
val json = request.body
val input = Json.fromJson[User](json)
input.asOpt match {
case Some(m: User) => Ok(f(m)).as("application/json")
case None => Ok("bad input")
}
}
def addUser = Action(parse.json) { common(Domain.adduser)(_) }
def authenticate = Action(parse.json) { common(Domain.authenticate)(_) }
+2
source to share