首页 > 其他 > 详细

Scala隐式转换

时间:2020-04-15 10:57:51      阅读:51      评论:0      收藏:0      [点我收藏+]

1.隐式值

object ScalaDemo {

  implicit val str : String = "刘明"

  def main(args: Array[String]): Unit = {
    //匹配隐式值时,不加括号
    show
  }

  def show(implicit name:String)={
    print("name: " + name)
  }
  
}

 

2.隐式方法

object ScalaDemo {

  def main(args: Array[String]): Unit = {
    val aa = new AA
    aa.methodAA()
    //创建了AA,经隐式方法转换,能调用BB里的方法
    aa.methodBB()
  }

  implicit def AB(a:AA):BB={
    new BB
  }
  
}

class AA {
  def methodAA(): Unit ={
    println("methodAA...")
  }
}

class BB {
  def methodBB(): Unit ={
    println("methodBB...")
  }
}

  

3.隐式类

object ScalaDemo {
  
  def main(args: Array[String]): Unit = {
    val aa = new AA
    aa.methodAA()
    //创建了AA,经隐式类的主构造器转换,能调用BB里的所有方法
    aa.methodBB()
    aa.methodBB2()
  }

  implicit class BB(aa: AA) {

    def methodBB(): Unit ={
      println("methodBB...")
    }
    
    def methodBB2(): Unit ={
      println("methodBB2...")
    }
  }

}

class AA {
  def methodAA(): Unit ={
    println("methodAA...")
  }
}

  

Scala隐式转换

原文:https://www.cnblogs.com/noyouth/p/12703328.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!