Scala隐式转换

1、隐式方法

package base

/**
  * @author yangwj
  * @date 2020/8/7 17:41
  */

object ImplicitDemo {

//  implicit class Caculate(x:Int) {
//
//    def add(y:Int):Int={
//      x+y
//    }
//  }

  //隐式方法
  object MyImplicitTypeConversion {
    implicit def strToInt(str: String) = str.toInt
  }

  def main(args: Array[String]) {
    import MyImplicitTypeConversion.strToInt
    val max = math.max("6", 2);
    println(s"max = ${max}")

//    val add: Int = 4.add("5")
//    println(s"add = ${add}")

  }
}

2、隐式类

package base

/**
  * @author yangwj
  * @date 2020/8/7 17:41
  */

object ImplicitDemo {
  
  //隐式类
  implicit class Caculate(x:Int) {
    def add(y:Int):Int={
      x+y
    }
  }

  //隐式方法
  object MyImplicitTypeConversion {
    implicit def strToInt(str: String) = str.toInt
  }

  def main(args: Array[String]) {
    import MyImplicitTypeConversion.strToInt
    val max = math.max("6", 2); //隐式方法使用
    println(s"max = ${max}")

    val add: Int = 4.add("5") //这里用到了隐式方法,也用到了隐式类
    println(s"add = ${add}") //

  }
}
原文地址:https://www.cnblogs.com/ywjfx/p/13468358.html