使用Scala Option验证命令行参数
发布时间:2020-12-16 09:05:28 所属栏目:安全 来源:网络整理
导读:我在 Scala实用程序应用程序中使用Apache commons CLI进行命令行解析.其中一个参数是数据库端口号(–port =),它覆盖了默认的“5432”(对于PostgreSQL).我正在尝试使用Option类来协助验证.这是我想出的代码.有更好的方法来进行验证吗? val port = Option(com
我在
Scala实用程序应用程序中使用Apache commons CLI进行命令行解析.其中一个参数是数据库端口号(–port =),它覆盖了默认的“5432”(对于PostgreSQL).我正在尝试使用Option类来协助验证.这是我想出的代码.有更好的方法来进行验证吗?
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之间的整数,包括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) 解决方法
我承认我不是百分百肯定,如果出现问题你想要抛出什么,或者5432是每个错误值的默认端口,但这是我要做的:
def getPort(candidate: Option[String]) = candidate .map { _.toInt } // throws NumberFormatException .filter { v => v > 0 && v <= 65535 } // returns Option[Int] .getOrElse { throw new IllegalArgumentException("error message") } // return an Int or throws an exception (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |