【发布时间】:2018-04-06 17:46:29
【问题描述】:
我有一些用户提供的值作为Option[String]。我只想在它们非空时验证它们。
验证只是检查字符串是否可以转换为int,并且不小于0。
有没有什么办法可以简化这段代码,或者让它更具可读性?
val top: Option[String] = ...
val skip: Option[String] = ...
val validationErrors = new ListBuffer[Err]()
top match {
case Some(x) => if (x.toIntOpt.isEmpty || x.toIntOpt.get < 0) validationErrors += PositiveIntegerRequired("$top")
}
skip match {
case Some(x) => if (x.toIntOpt.isEmpty || x.toIntOpt.get < 0) validationErrors += PositiveIntegerRequired("$skip")
}
这里是 toIntOpt 助手:
def toIntOpt: Option[Int] = Try(s.toInt).toOption
【问题讨论】:
-
object PositiveInt { def unapply(repr: String): Option[Int] = Try(repr.toInt).filter(_ >= 0)和top match { case Some(PositiveInt(x)) => ???; case _ => sys.error(s"Invalid int: $repr") }
标签: scala functional-programming pattern-matching