【发布时间】:2020-06-16 10:49:15
【问题描述】:
我有一个函数,我需要在其中组合来自两个 Either 对象的结果。
如果“handlingResult”是Right,我需要“request”的右侧,并且如果“handlingResult”是Right,“request”也是Right,这是一个既定事实。
如果“handlingResult”为左,我需要它的值来构建响应。
现在这是实现(FailingResponse 和 SuccessResponse 都扩展了 ValuationResponse):
def getResponse(handlingResult : Either[FailureReason, List[StockValuation]]
,request : Either[Error, ValuationRequest]
): ValuationResponse = {
handlingResult.fold(
failureReason =>
FailingResponse(failureReason.message
,failureReason.statusCode),
listOfValuations =>
SuccessfulResponse(listOfValuations
,request.right.get.symbol
,request.right.get.function
,StatusCodes.SUCCESS))
}
但我怀疑直接访问 any 不是一个好习惯,例如在
request.right.get.symbol
什么是实现相同行为但以可推荐的方式进行的好方法?
【问题讨论】:
标签: scala functional-programming monads either