查看Functional Programming in Scala的Validation
特征:
sealed trait Validation[+E, +A]
case class Failure[E](head: E, tail: Vector[E]) extends Validation[E, Nothing]
case class Success[A](a: A) extends Validation[Nothing, A]
我的不完整的理解是这个特性使用类型E and children
和A and children
- 协变。
我可以通过以下方式实例化Success
val s = Success("winner")
但是,我如何实例化Failure
?我试过了:
val f = Failure[String]("lose", Vector("lost"))
但是,当我尝试将f
作为fb
参数输入map2
时,它失败了:
override def map2[A,B,C](fa: Validation[E,A], fb: Validation[E,B])(f: (A, B) => C)
scala> validation.map2(s, failure)( (a: String, b: String) => a + b)
<console>:17: error: type mismatch;
found : DataType.DataType.Failure[String]
required: DataType.DataType.Validation[Nothing,?]
validation.map2(s, failure)( (a: String, b: String) => a + b)