You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中如何将Future[Either[Throwable,T]]转换为Either[Throwable,T]

解决Scala中Future[Either]的解包与函数调用问题

你的核心问题是没有正确在map中传递Future内部的Either值给anotherFunc,原来的写法存在语法逻辑错误,下面是正确的实现方式:

正确写法1:显式参数传递

myFunc("some string").map { eitherResponse =>
  anotherFunc(eitherResponse)
}

正确写法2:函数引用简化

因为anotherFunc的参数类型正好匹配Future内部的Either[Throwable, HttpResponse]类型,所以可以直接传递函数引用,代码更简洁:

myFunc("some string").map(anotherFunc)

补充说明

如果anotherFunc的返回值是Unit(无返回值),使用foreach会比map更符合语义:

myFunc("some string").foreach(anotherFunc)

原写法错误原因

你原来的代码:

myFunc("some string").map { _ =>
  anotherFunc(_)
}

这里的第二个_并不是指代map接收的Either值,而是会被Scala解析为一个新的匿名函数参数,相当于创建了一个逻辑完全偏离的匿名函数,自然无法满足传递Either值的需求。

内容的提问来源于stack exchange,提问作者sharingiscaring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:09:11