作用域
在实际的操作过程中,我们建议把它定义在如下两个地方:
1.包对象。这样在这个包下的所有类和对象中都可以使用,并且不需要额外的引入语句。
- 一个单独的文件定义中。这样在其他需要的位置就可以直接导入,然后使用。
package imp
object imps {
implicit class StrongInt(n: Int) {
def ! : Int = {
var rst = 1
for (i <- 1 to n) {
rst *= i
}
rst
}
}
implicit class StrongString(s: String) {
def isPhone: Boolean = {
val reg = "^[135678]\d{9}$".r
reg.matches(s)
}
def isIDCard: Boolean = {
val reg = "^[1-9]\d{5}([181920])\d{2}((0[1-9])|(1[0-2]))((0[1-9]|[1-9])|10|20|30|31)\d{3}[0-9Xx]$".r // 身份证号的正则表达式
reg.matches(s)
}
}
}
package imp
import scala.language.postfixOps
import imp.imps._
object imp07 {
def main(args: Array[String]): Unit = {
println(4!) // 24
println(5!) // 120
println("13614254566".isPhone)
}
}