• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

大数据:Scala 隐式转换 完整使用(第十章)

武飞扬头像
小坏讲微服务
帮助2

一、隐式转换

当编译器第一次编译失败的时候,会在当前的环境中查找能让代码编译通过的方法,用
于将类型进行转换,实现二次编译

1、隐式函数

1)说明

隐式转换可以在不需改任何代码的情况下,扩展某个类的功能。

2)案例实操

需求:通过隐式转化为 Int 类型增加方法。

// 当想调用对象功能时,如果编译错误,那么编译器会尝试在当前作用域范
围内查找能调用对应功能的转换规则,这个调用过程是由编译器完成的,所以称之为隐
式转换。也称之为自动转换

package chapter09plus

/**
 * 隐式函数和隐式类型
 */
object Test02_Implicit {
  def main(args: Array[String]): Unit = {

    //0、普通
    val new12 = new MyRichInt(12)
    println(new12.myMax(15))


    //1、隐式函数
    implicit def convert(num: Int): MyRichInt = new MyRichInt(num)

    println(12.min(15))

    println("------------------------------------")
    println(12.min(15))

  }
}


//自定义类
class MyRichInt(val self: Int) {
  //自定义比较大小的方法
  def myMax(n: Int): Int = if (n < self) self else n
  def myMin(n: Int): Int = if (n < self) n else self
}

学新通

1、隐式类

1)案例实操

package chapter09plus

/**
 * 隐式函数和隐式类型
 */
object Test02_Implicit {
  def main(args: Array[String]): Unit = {

    println("----------------隐式类--------------------")
    //2、隐式类
    implicit class MyRichInt2(val self: Int) {
      //自定义比较大小的方法
      def myMax2(n: Int): Int = if (n < self) self else n
      def myMin2(n: Int): Int = if (n < self) n else self
    }

    println(12.myMax2(15))
  }
}
学新通

3、隐式参数

package chapter09plus

/**
 * 隐式函数和隐式类型
 */
object Test02_Implicit {
  def main(args: Array[String]): Unit = {

    //3、隐式参数
    //只关心参数类型
    implicit val str: String = "alice"
    implicit val num: Int = 18

    def sayHello(implicit name: String): Unit = {
      println("hello, "   name)
    }

    def sayHi(implicit name: String = "alice"): Unit = {
      println("hi, "   name)
    }

    sayHello
    sayHi()


    //4、简便写法 ----> implicitly[Int] 预先定义好的参数
    def hiAge(): Unit = {
      println("hi, "   implicitly[Int])
    }

    hiAge()
  }
}
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbhegk
系列文章
更多 icon
同类精品
更多 icon
继续加载