隐式转换函数补充

64 阅读1分钟

隐式转换函数案例

  • 目标:已有一个写好的类,要求在不修改这个类的源代码的情况下,拓展这个类的新功能。
  • 思路:
    1. 补充定义一个新类,在这个新类中提供新方法;
    1. 提供一个隐式转换函数,把之前旧类对象转换成这个新类对象。
object imp04 {
  class User() {
    def insertUser():Unit = {
      println("insertUser......")
    }
  }

  class UserStrong() {
    def updateUser():Unit = {
      println("updateUser......")
    }
  }

  implicit def xxxxx(user:User):UserStrong = {
    println("自动调用隐式转换函数......")
    new UserStrong
  }

  def main(args: Array[String]): Unit = {
    val u1 = new User()
    u1.insertUser()
    // val u2 = new UserStrong()
    u1.updateUser()
    // u2.updateUser()
  }
}

综合使用 代入文件

图片示例:

屏幕截图 2025-12-30 101310.png

代码如下:

import scala.language.postfixOps
import imp.imps._

object imp07 {
  def main(args: Array[String]): Unit = {
    println(4!) // 24
    println(5!) // 120
    println("13614254456".isPhone)
  }
}

被代入文件:

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 = "^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[1-9])|([1-2][0-9])|(3[0-1]))\d{3}[0-9Xx]$".r // 身份证号的正则表达式
      reg.matches(s)
    }
  }
}