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

问题描述 投票:0回答:1

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

override def getUsers(organization: String, params: String): F[Either[CodecException, List[Users]]] = for {
    resp <- getUsersFromClient(organization, params)
    result <- Sync[F].delay(decodeResponseEntity(resp), CodecException.withMessage("Something goes wrong while decoding response."))
  } yield result

  override def getAnimals(url: String, params: String): F[Either[CodecException, List[Animal]]] = for {
    resp <- getAnimalsFromClient(url, params)
    result <- Sync[F].delay(decodeResponseContributor(resp), CodecException.withMessage("Something goes wrong while decoding response."))
  } yield result

而且我认为我应该以某种方式将它们重构为implicits仅具有一种方法或某种方法,但是我不知道应该如何以正确的方式进行操作以保持功能风格。您能帮我吗?

scala refactoring scala-cats
1个回答
0
投票

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

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

def get[A](a: String, params: String, getFromClient: (String, String) => ..., decodeResponse: ... => ...): F[Either[CodecException, List[A]]] = for {
  resp <- getFromClient(a, params)
  result <- Sync[F].delay(decodeResponse(resp), CodecException.withMessage("Something goes wrong while decoding response."))
} yield result
© www.soinside.com 2019 - 2024. All rights reserved.