隐式函数2

77 阅读1分钟

转换规则

隐式转换确实非常的强大,但是,在具体的使用过程中,我们要遵循一些特定的转换规则。

具体来说有两点:无歧义规则,不能多次转换。下面我们分别来解释

规则1:无歧义规则:不能重新定义两个相同的转换函数。如果有两个隐式转换函数,只有函数名不同,则会导致错误

object imps {
  implicit class StrongInt(n: Int) {
    def ! : Int = {
      var res = 1
      for (i <- 1 to n) {
        res *= i
      }
      res
    }
  }

  implicit class StrongString(s: String) {
    def isPhone: Boolean = {
      val reg = "^[1][35678]\d{9}$".r
      reg.matches(s)
    }

    def isIDCard: Boolean = {
      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}[0-9Xx]$".r // 身份证号的正则表达式
      reg.matches(s)
    }
  }
}

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

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

import imp.imps._
object imp07 {
  def main(args: Array[String]): Unit = {

    println(4!) // 24
    println(5!) // 120

    println("13512456789".isPhone)
  }
}