【发布时间】:2014-01-25 13:51:05
【问题描述】:
假设我有几个案例类和函数来测试它们:
case class PersonName(...)
case class Address(...)
case class Phone(...)
def testPersonName(pn: PersonName): Either[String, PersonName] = ...
def testAddress(a: Address): Either[String, Address] = ...
def testPhone(p: Phone): Either[String, Phone] = ...
现在我定义了一个新的案例类 Person 和一个测试函数,很快就失败了。
case class Person(name: PersonName, address: Address, phone: Phone)
def testPerson(person: Person): Either[String, Person] = for {
pn <- testPersonName(person.name).right
a <- testAddress(person.address).right
p <- testPhone(person.phone).right
} yield person;
现在我希望函数testPerson 累积错误,而不是快速失败。
我希望testPerson 始终执行所有这些test* 函数并返回Either[List[String], Person]。我该怎么做?
【问题讨论】:
-
我知道这不是你想听到的,但错误累积和
for-comprehensions(或任何类型的单子排序)只是不混合。例如,如果您在对testAddress的调用中使用了pn并且testPersonName失败了怎么办? -
看看
ValidationNel来自scalaz。见Learning scalaz/Validation。在你的情况下:def tesPersonName(pn: PersonName): ValidationNel[String, PersonName] = ...=>(testPersonName(person.name) |@| testAddress(person.address) |@| testPhone(person.phone))(Person). -
你也可以看看this library。它允许您以您想要的方式组合
Either:Right(Person)(testPersonName(person.name), testAddress(person.address), testPhone(person.phone))。免责声明:我没有尝试过这个库。
标签: scala functional-programming either