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
|