Scala-如何以功能样式重构代码

我创建了两种类似的方法:

override def getUsers(organization: String,params: String): F[Either[CodecException,List[Users]]] = for {
    resp <- getUsersFromClient(organization,params)
    result <- Sync[F].delay(resp)
  } yield result

  override def getanimals(url: String,List[Animal]]] = for {
    resp <- getanimalsFromClient(url,params)
    result <- Sync[F].delay(resp)
  } yield result

我认为我应该以某种方式将它们重构为implicits仅具有一种方法或某种方法,但是我不知道应该如何以正确的方式完成功能样式的重构。你能帮我吗?

编辑:

def getUsersFromClient(param1: String,params: String): F[HttpResponse] = Hammock.getWithOpts(...)

def getanimals(param1: String,params: String): F[HttpResponse] = Hammock.getWithOpts(...)

此方法也相似,并返回F[HttpResponse]

wdwxhn 回答:Scala-如何以功能样式重构代码

很难说,因为您没有提供getUsersFromClientgetAnimalsFromClientdecodeResponseEntitydecodeResponseContributor ...

例如,您可以尝试使方法通用且高阶

def get[A](s: String,params: String,getFromClient: (String,String) => ...,decodeResponse: ... => ...): F[Either[CodecException,List[A]]] = for {
  resp <- getFromClient(s,params)
  result <- Sync[F].delay(decodeResponse(resp),CodecException.withMessage("Something goes wrong while decoding response."))
} yield result
本文链接:https://www.f2er.com/3122805.html

大家都在问