Scala-Cats:-是否可以合并来自不同NonEmptyLists的错误?

时间:2018-09-19 13:03:19

标签: scala scala-cats

是否有可能使用NonEmptyList组合来自多个变量的不同错误

type ValidationResult[A] = ValidatedNel[String, A]

def throwErrorsWhenNumberIsLessThan6(x:Int):ValidationResult[Int] = if(x<6) s"$x !> 6".invalidNel else (x+6).validNel

def throwErrorsWhenStringLengthIsLessThan6(x:String):ValidationResult[String] = if(x.length<6) s"$x length > 6".invalidNel else (x+" OK!!! ").validNel

val ints = Range.apply(1,10).map(throwErrorsWhenNumberIsLessThan6).toList

val strings = Range.apply(1,10).map(e => throwErrorsWhenStringLengthIsLessThan6(e.toString)).toList

是否有一种方法可以合并intsstrings中所有可用的错误?

假设intsstringsNonEmptyList中将具有相同的数据类型。

2 个答案:

答案 0 :(得分:0)

这对我有用

type ValidationResult[A] = ValidatedNel[String, A]
def throwErrorsWhenNumberIsLessThan6(x:Int):ValidationResult[Int] = if(x<6) s"$x !> 6".invalidNel else (x+6).validNel
def throwErrorsWhenStringLengthIsLessThan6(x:String):ValidationResult[String] = if(x.length<6) s"$x length > 6".invalidNel else (x+" OK!!! ").validNel

val ints = Range.apply(0,2).map(throwErrorsWhenNumberIsLessThan6).toList
val strings = Range.apply(0,2).map(e => throwErrorsWhenStringLengthIsLessThan6(e.toString+"KK")).toList

ints.filter(_.isInvalid).:::(strings.filter(_.isInvalid))
//List(Invalid(NonEmptyList(0KK length > 6)), Invalid(NonEmptyList(1KK length > 6)), Invalid(NonEmptyList(0 !> 6)), Invalid(NonEmptyList(1 !> 6)))

答案 1 :(得分:0)

是的,您可以使用Applicative类型类中的方法。

例如,现在您的ints的类型为List[ValidationResult[Int]]。您可以使用sequence方法将其转换为ValidationResult[List[Int]]

import cats.implicits._

scala> val validatedInts = ints.sequence

validatedInts: ValidationResult[List[Int]] =
  Invalid(NonEmptyList(1 !> 6, 2 !> 6, 3 !> 6, 4 !> 6, 5 !> 6))

或者,在创建traverse对象以立即获得map时,可以使用ints代替ValidationResult

scala> val validatedInts2 = (1 until 10).toList.traverse(throwErrorsWhenNumberIsLessThan6)

validatedInts2: ValidationResult[List[Int]] = 
  Invalid(NonEmptyList(1 !> 6, 2 !> 6, 3 !> 6, 4 !> 6, 5 !> 6))

并对strings执行相同操作:

scala> val validatedStrings = (0 until 2).toList.traverse(e =>
  throwErrorsWhenStringLengthIsLessThan6(e.toString + "KK")).toList

validatedStrings: ValidationResult[List[String]] = 
  Invalid(NonEmptyList(0KK length > 6, 1KK length > 6))

现在您可以使用validatedIntsvalidatedStrings方法将ValidationResultmapN合并为一个tupled

scala> (validatedInts, validatedStrings).tupled
res0: ValidationResult[(List[Int], List[String])] = 
  Invalid(NonEmptyList(1 !> 6, 2 !> 6, 3 !> 6, 4 !> 6, 5 !> 6, 0KK length > 6, 1KK length > 6))

scala> (validatedInts, validatedStrings).mapN(_.map(_.toString) ++ _)
res1: ValidationResult[List[String]] = 
  Invalid(NonEmptyList(1 !> 6, 2 !> 6, 3 !> 6, 4 !> 6, 5 !> 6, 0KK length > 6, 1KK length > 6))