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


I'm new to Scala too, but I think we can do something like this. Please correct me if I am wrong.

You can do something like this



def foo(f:Int=>Int,x:Int):Int = {f(x)}
   foo(x=>x+x,3)

      

In the same way, you can pass the function you want to call into a generic function.

0


source







All Articles