Scala 使用EitherT-s inside对comp进行数据验证
考虑一下我试图解决的问题的简化版本。这是我当前的实现Scala 使用EitherT-s inside对comp进行数据验证,scala,validation,design-patterns,functional-programming,for-comprehension,Scala,Validation,Design Patterns,Functional Programming,For Comprehension,考虑一下我试图解决的问题的简化版本。这是我当前的实现 case class Foo() def addFoo(json: String): EitherT[Future, Exception, Long] = { def parse(json: String): EitherT[Future, Exception, Foo] = ??? def validate(foo: Foo): EitherT[Future, Exception, Foo] = ??? def save(
case class Foo()
def addFoo(json: String): EitherT[Future, Exception, Long] = {
def parse(json: String): EitherT[Future, Exception, Foo] = ???
def validate(foo: Foo): EitherT[Future, Exception, Foo] = ???
def save(foo: Foo): EitherT[Future, Exception, Long] = ???
for {
foo <- parse(json)
_ <- validate(foo)
id <- save(foo)
} yield id
}
case类Foo()
def addFoo(json:String):EitherT[Future,Exception,Long]={
def parse(json:String):EitherT[Future,Exception,Foo]=???
def验证(foo:foo):EitherT[Future,Exception,foo]=???
def save(foo:foo):EitherT[未来、异常、长]=???
为了{
foo如果您不关心正确的值,您可以使用Unit
而不是foo
,例如:
def validate(foo: Foo): EitherT[Future, Exception, Unit] = ???
您可以更改validate
的类型签名以添加更多类型安全性:
def-validate(foo:foo):EitherT[未来、异常、有效foo]
其中ValidFoo
如下所示:
object ValidFoo {
def believeMeItsValid(raw: Foo): ValidFoo = new ValidFoo(raw)
}
class ValidFoo private (val foo: Foo)
而save
将只接受已验证的输入:
def save(foo:ValidFoo):EitherT[未来、异常、长]
这将迫使您在保存输入之前验证输入,并有助于防止布尔盲