首页 > 其他 > 详细

scala中隐式转换之隐式值和隐式视图

时间:2017-12-07 20:24:21      阅读:284      评论:0      收藏:0      [点我收藏+]
/**
  * Created by root
  * Description : 隐式值和隐式视图
  */
object ImplicitTest {

  def main(args: Array[String]): Unit = {

    // 隐式值
    implicit val str = "hello"
    def fun(implicit s: String) = println(s)
    fun  // 调用fun函数,编译器发现参数缺省,直接去作用域内查找隐式值,保证隐式值只有一个

    // 隐式视图:隐式转换为目标类型:把一种类型自动转换到另一种类型
    implicit def intToString(a : Int) = a.toString
    implicit def intToByte(a : Int) = a.toByte
    def fun2(s: String) = println(s)
    fun2(100) //调用fun2函数,参数是个整数,编译器发现函数参数类型不一致,直接去作用域内查找符合编译通过的类型

  }

}

 

scala中隐式转换之隐式值和隐式视图

原文:http://www.cnblogs.com/xubiao/p/8000359.html

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