scala - cats.data.EitherT with traverse
问题描述
I have a question about using Traverse together with EitherT. Let's say we have a code like this:
def validate(s: String): EitherT[Future, NumberFormatException, Int] = {
EitherT(Future.successful(try { Right(s.toInt) } catch { case e:
NumberFormatException => Left(e)}))
}
List("1", "2").traverse(validate)
Unfortunately this code does not compile, because we are missing something:
error: could not find implicit value for evidence parameter of type cats.Applicative[G] List("1", "2").traverse(validate)
I tried to look this up and found for example this answer: Switching between EitherT and Validation to accumulate error or traverse or Validation versus disjunction
So it seems some solution could exists. But the problem is that both of them are using traverseU, which is no longer an option in scala 2.12. So how can this be done please?
EDIT This is the code including imports:
import cats.data.EitherT
import cats.syntax.traverse._
import cats.instances.list._
import cats.instances.future._
import scala.concurrent.ExecutionContext.global
import scala.concurrent.Future
def validate(s: String): EitherT[Future, NumberFormatException, Int] = {
EitherT(Future.successful(try { Right(s.toInt) } catch { case e:
NumberFormatException => Left(e)}))
}
List("1", "2").traverse(validate)
解决方案
通常猫会在不同的导入下打包特定的证据隐含。在这种情况下,您需要 和 的List
证明Future
。
import cats.data.EitherT
import cats.syntax.traverse._
import cats.instances.list._
import cats.instances.future._
import scala.concurrent.Future
def validate(s: String): EitherT[Future, NumberFormatException, Int] = {
EitherT(Future.successful(try { Right(s.toInt) } catch { case e: NumberFormatException => Left(e) }))
}
List("1", "2").traverse(validate)
这段代码对我来说是用猫 1.2.0 编译的。
推荐阅读
- laravel - 如何在 Laravel 外部的包中使用 Laravel 外观(缓存、日志、存储)
- ios - How would I create the visual equivalent of a UIView in SwiftUI?
- java - 添加 NavigationItemSelectedListener 后菜单项不会变为活动状态
- html - `innerHTML` 不适用于 `input` 标签,但 `value` 可以
- java - Spring JPA 中的方法名称太长
- c# - 使用定时器和任务的 Arduino 到 C# 实时数据传输
- java - @RequestBody 应该用 Spring Webflux 中的 Mono Publisher 包装吗?
- r - 定义一个新变量来计算另一列的组元素
- typescript - 为什么 TypeScript 中的 instanceof 不适用于继承的类?
- ios - 反应本机 - 在 ios 中未调用关闭事件时的 Web 套接字