我正在使用Apache commons CLI在Scala实用程序应用程序中进行命令行分析。其中一个参数是覆盖缺省“5432”(用于PostgreSQL)的数据库端口号(--port=
)。我正在尝试使用Option类来协助验证。这是我想出的代码。有没有更好的方法来进行验证?使用Scala选项来验证命令行参数
val port = Option(commandLine.getOptionValue("port", "5432")) map {
try {
val value = Integer.parseInt(_)
if (value < 1 || value > 65535) throw new NumberFormatException
value
} catch {
case ex: NumberFormatException =>
throw new
IllegalArgumentException("the port argument must be a number between 1 and 65535")
}
} get
端口号必须是1到65535(含)之间的整数。
这样做会更好吗?为什么或者为什么不?
val port = Option(commandLine.getOptionValue("port")) map {
try {
val value = Integer.parseInt(_)
if (value < 1 || value > 65535) throw new NumberFormatException
value
} catch {
case ex: NumberFormatException =>
throw new
IllegalArgumentException("the port argument must be a number between 1 and 65535")
}
} getOrElse(5432)
我在标准库中缺少的是'String => Option [Int]'方法。 – ziggystar
@ziggystar:如果你可以使用Scalaz,它有一个方法'parsent:String => Validation [NumberFormatException,Int]'。在验证中调用'toOption'会给你'Option [Int]'。 – missingfaktor