隐式转换
定义:
简单RichFile增加read方法:
package com.billstudy.scala.implicits
import java.io.File
import scala.io.Source
/**
* Created by Bill on 2015-07-02 20:11
* 原生的java.io.File没有直接read的方法,通过定义RichFile增强实现Read隐式函数进行增强
* Email: LuckyBigBill@gmail.com
*/
class RichFileBaseImplicit(f: File){
def read = Source.fromFile(f).mkString
}
object RichFileBaseImplicitContent{
implicit def file2RichFile(f: File) = new RichFileBaseImplicit(f)
}
object RichFileBaseImplicit{
import RichFileBaseImplicitContent.file2RichFile
def main(args: Array[String]) {
val content = new File("F:/word.txt").read
println(content)
}
}
Scala引入隐式转换:
隐式转换规则(3种):