Scala implicit 小结 隐式类 隐式函数 隐式值 隐式参数

 1. 隐式类  implicit class   丰富一个类的方法

object Test {
  def main(args: Array[String]): Unit = {
    100.run
    100.marry
  }
  

  implicit class AddFunctionToInt(i:Int){
    def run ={
      println(s"整数${i} run起来了")
    }

    def marry={
      println(s"整数${i} 结婚了")
    }
  }
}

结果:

整数100 run起来了
整数100 结婚了

笔记:

增加(丰富 enrich)一个类的功能,类似于 iOS中的 category

2. implicit def  隐式函数   偷偷摸摸地执行某个方法

object Test {
  def main(args: Array[String]): Unit = {
    println(add("3",4))
  }

  def add(a:Int,b:Int):Int ={
    a+b
  }

  implicit def stringToInt(a:String):Int = {
    Integer.parseInt(a)
  }
}

结果是 7 ,尽管add 只能接收 Int 类型的参数,但是在程序执行的背景下面,有一个 隐式函数,并且是针对 String类型的,

编译器就会对这个"3"做手脚,将其转换成Int类型。

3. implicit 参数

object Test {
  def main(args: Array[String]): Unit = {
    implicit val a = 100
    increment
    println(increment)
  }

  def increment(implicit x:Int): Int ={
    x+1
  }
}

执行结果: 1

我们执行 increment 这个函数的时候居然没有 传参数,为什么?因为他接收一个隐式的参数,所以可以不传,increment 根据上下文环境,会将一个隐式值 放到 这个参数里面。

下面再做一个实验:

object Test {
  def main(args: Array[String]): Unit = {
    implicit val a = 100
    implicit val b = 200
    increment
    println(increment)
  }

  def increment(implicit x:Int): Int ={
    x+1
  }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值