我想定义一个包装mac地址的类:
class MacAddress(macAddress: String)
但是,我想检查作为参数传递的值确实是一个mac地址。这是否有意义,如果是这样,在Scala中实现这一目标的正确方法是什么?
我能想到的最好的是:
class MacAddress private (macAddress: String)
object MacAddress {
// TODO: Here we would validate that the passed string is indeed a MAC address.
def apply(macAddress: String): Try[MacAddress] = ???
}
答案 0 :(得分:1)
您可以使用require
来验证参数。这是一个正则表达式的例子:
case class MacAddress(macAddress: String) {
require(macAddress.matches("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"), "Invalid mac address")
}
用法:
scala> MacAddress("00:0a:95:9d:68:1A")
res11: MacAddress = MacAddress(00:0a:95:9d:68:1A)
scala> MacAddress("00:0a:95:9d:68:1Z")
java.lang.IllegalArgumentException: requirement failed: Invalid mac address
at scala.Predef$.require(Predef.scala:277)
... 28 elided