隐式案例

28 阅读1分钟

一、案例:验证字符串是否手机号

需求: 让所有的字符串都具备一个功能:检查自己是不是一个合法的手机号码?

1.目前的字符串类是没有这个功能的。

2.拓展String这个类。

object imp05 {

  //让所有的String对象,都有了一个新的方法 isPhone!
  implicit class StrongString(s:String) {
    def isPhone():Boolean = {
      val reg = "^1[356789]\d{9}$".r
      reg.matches(s)
    }
  }
  def main(args: Array[String]): Unit = {
    val str = new String("13612345678")

    var str1 = "abaadsfsdfs"

    //判断自己是否是一个手机号
    if(str1.isPhone){
      println(s"${str1}是手机号")
    }else{
      println(s"${str1}不是手机号")
    }
  }
}

二、案例:计算阶乘

需求: 让所有的整数都具备一个功能:计算阶乘。

n! = 1 * 2 * 3 * 4 * .... * n

1.目前的整数类是没有这个功能的。

2.拓展Int这个类。

import scala.language.postfixOps
object imp06 {

  implicit class StrongInt(n:Int) {
    def !(): Int = {
     // println("阶乘....")
      var s = 1
      for(i <-1 to n){
        s *= i
      }
      s
    }
  }
  def main(args: Array[String]): Unit = {
    var k = 5;

    //计算k的阶乘
    printf(s"${k}的阶乘是:${k.!()}")
  }
}