2
我有这样一段代码猫斯卡拉猫:是否有确保方法吗?
现在,因为异或已被删除的Xor
对象上,我试图用写类似的东西任一对象
Either.ensuring(name.nonEmpty, List(s"$name cannot be blank"))
但这不起作用因为保证的退货类型是Either.type
我可以写if。但我想用猫的结构做验证。
我有这样一段代码猫斯卡拉猫:是否有确保方法吗?
现在,因为异或已被删除的Xor
对象上,我试图用写类似的东西任一对象
Either.ensuring(name.nonEmpty, List(s"$name cannot be blank"))
但这不起作用因为保证的退货类型是Either.type
我可以写if。但我想用猫的结构做验证。
Xor
已从猫身上移除,因为Either
现在在Scala 2.12中是右偏的。您可以使用标准库Either#filterOrElse
,它做同样的事情,但没有咖喱:
val e: Either[String, List[Int]] = Right(List(1, 2, 3))
val e2: Either[String, List[Int]] = Right(List.empty[Int])
scala> e.filterOrElse(_.nonEmpty, "Must not be empty")
res2: scala.util.Either[String,List[Int]] = Right(List(1, 2, 3))
scala> e2.filterOrElse(_.nonEmpty, "Must not be empty")
res3: scala.util.Either[String,List[Int]] = Left(Must not be empty)
使用猫,你可以使用Either
ensure
,如果参数和缺乏钻营的顺序是不您的喜好:
import cats.syntax.either._
scala> e.ensure("Must be non-empty")(_.nonEmpty)
res0: Either[String,List[Int]] = Right(List(1, 2, 3))