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))