如何在Scala中编写此验证逻辑?
发布时间:2020-12-16 18:58:41 所属栏目:安全 来源:网络整理
导读:假设我想在 Scala中编写以下逻辑 val xdir = System.getProperty("XDir")if (xdir == null) error("No XDir") // log the error and exitval ydir = System.getProperty("YDir") if (ydir == null) error("No YDir")if (!new File(xdir).isDirectory) error(
假设我想在
Scala中编写以下逻辑
val xdir = System.getProperty("XDir") if (xdir == null) error("No XDir") // log the error and exit val ydir = System.getProperty("YDir") if (ydir == null) error("No YDir") if (!new File(xdir).isDirectory) error("XDir is not a directory") if (!new File(ydir).isDirectory) error("YDir is not a directory") if (!new File(xdir).exists) error("XDir does not exis") if (!new File(ydir).exists) error("YDir does not exist") ... (and so on) 在Scala中编写此验证链的最佳方法是什么? 解决方法
这里有一些有用的东西:
def sysValue(prop: String) = Option(System.getProperty(prop)) //returns Option[String] def trySysValue(prop: String) = //returns Either[String,String] sysValue(prop) map Right getOrElse Left("Absent property: " + prop) 然后你可以通过它的右投影使用Eadadadic组合 val batch = //batch is Either[String,(File,File)] for { x <- trySysValue("XDir")).right xf <- dir(x).right y <- trySysValue("YDir").right yf <- dir(y).right } yield (xf,yf) 哪里: def dir(s: String) = { //returns Either[String,File] val f = new File(s) if (!f.exists()) Left("Does not exist: " + f) else if (!f.isDir()) Left("Is not a directory: " + f) else Right(f) } Either的左侧将是错误消息.这种monadic组合快速失败.您可以使用scalaz验证来实现将累积所有失败的组合(例如,如果XDir和YDir都不存在,您将看到两个消息).在这种情况下,代码看起来像这样: def trySysValue(prop: String) = //returns Validation[String,String] sysValue(prop) map Success getOrElse ("Absent property: " + prop).fail def dir(s: String) = { val f = new File(s) if (!f.exists())("Does not exist: " + f).fail else if (!f.isDir()) ("Is not a directory: " + f).fail else f.success } val batch = //batch is ValidationNEL[String,File)] (trySysValue("XDir")) flatMap dir).liftFailNel <|*|> (trySysValue("YDir")) flatMap dir).liftFailNel (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |