隐式转换和隐式参数
-
作用:能够丰富现有类库的功能,对类的方法进行增强
-
隐式转换函数:以implicit关键字声明并带有单个参数的函数
package test
import scala.io.Source
/**
* @author: whua
* @create: 2018/10/08 15:29
*/
class RichFile(val file: String) {
def read(): String = {
Source.fromFile(file).mkString
}
}
object RichFile {
def main(args: Array[String]): Unit = {
/**
* 这个过程是显式地实现了read方法
*/
val file1 = "/Users/whua/Documents/tmpTest/word.txt"
val content1: String = new RichFile(file1).read()
println(content1)
/**
* 隐式地实现read方法(隐式转换)
*/
import MyPredef.fileToRichFile
val file = "/Users/whua/Documents/tmpTest/word.txt"
val content = file.read()
println(content)
}
}
package test
/**
* @author: whua
* @create: 2018/10/08 15:56
*/
object MyPredef {
implicit def fileToRichFile(file: String) = new RichFile(file)
}