分享

scala 学习总结(一): implicit 函数的使用

 看风景D人 2016-10-07

1、implicit 常见的用法

  关键字implicit用来标记一个隐式定义。编译器才可以选择它作为隐式变化的候选项。你可以使用implicit来标记任意变量,函数或是对象。
1. 使用implicit 可以实现——隐式参数

object ImplicitTest {
  /**
    * Implicit实现隐式参数
    */
    object Context{
    implicit val str:String = "implicit parameter"
   }
  object Parameter{
    def print(context:String)(implicit prefix:String): Unit ={
      println(prefix+":"+context)
    }

  }

  def main(args: Array[String]) {
    Parameter.print("Hello")("Scala")
    //在此使用隐式参数
    import Context._
    Parameter.print("Scala")
  }

}
/***************************************************/
运行结果:
Scala:Hello
implicit parameter:Scala
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

2.使用implicit 可以实现—— 隐式转换

示例一:

class RichFile(val file:File){
  def read= Source.fromFile(file.getPath).mkString
}

object Context{

  implicit def file2RichFile(f:File)=new RichFile(f)
}
object ImplicitDemo {

  def main(args: Array[String]) {
    /**
      * 在此使用了隐式转换
      */
    import  Context.file2RichFile
    println(new File("c://user//document.txt").read)
  }

}
/********************************************************/
示例二:
class ImplicitTransform {
  def display(str:String)=println(str)

  /**
    *隐式转换函数
    */
  implicit def typeConvertor(arg:Int) =arg.toString
  implicit def typeConvertor(arg:Boolean)=if(arg) "true" else "false"


  def main(args: Array[String]) {
    display(123)
  }
}
备注:
 1.隐式转换函数个函数名无关,只与传入参数类型和返回类型有关
 2.在同一个函数作用域下,不能同时有两个相同输入类型和返回类型的函数
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多