隐式函数2

57 阅读1分钟

作用域

1.包对象。这样在这个包下的所有类和对象中都可以使用,并且不需要额外的引入语句。

  1. 一个单独的文件定义中。这样在其他需要的位置就可以直接导入,然后使用

Snipaste_2025-12-30_10-19-25.png

package imp
import scala.language.postfixOps

import imp.imps._

object imp0 {
  def main(args: Array[String]): Unit = {
    println(4!) // 24
    println(5!) // 120

    println("13614254566".isPhone)
  }
}
package imp

object imps {
  // 为Int扩展阶乘方法的隐式类
  implicit class StrongInt(n: Int) {
    def ! : Int = {
      var rst = 1
      // 修正循环语法:Scala中正确写法是i <- 1 to n
      for (i <- 1 to n) {
        rst *= i
      }
      rst
    }
  }

  // 为String扩展手机号、身份证校验的隐式类
  implicit class StrongString(s: String) {
    // 手机号校验方法
    def isPhone: Boolean = {
      // 修正正则表达式(匹配国内手机号,示例规则)
      val reg = "^1[356789]\d{9}$".r
      reg.matches(s)
    }

    // 身份证号校验方法
    def isIDCard: Boolean = {
      // 18位身份证正则(含基本格式校验)
      val reg = "^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dXx]$".r
      reg.matches(s)
    }
  }
}