zoukankan      html  css  js  c++  java
  • 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}") //
    
      }
    }
  • 相关阅读:
    Oracle 数据库简介
    Qt 中事件与处理
    npm常用命令总结
    自适应宽度布局
    原生js发送ajax请求
    微信调试本地环境代码
    多行文本溢出显示省略号
    清除浮动
    用JQuery动态为选中元素添加/删除类
    input中加入搜索图标
  • 原文地址:https://www.cnblogs.com/ywjfx/p/13468358.html
Copyright © 2011-2022 走看看