Scala 隐式转换案例(一)
让 File 类具备 RichFile 类中的 read 方法
package cn.cheng.implic_demo
import java.io.File
import scala.io.Source
object MyPredef{
//定义隐式转换方法
implicit def file2RichFile(file: File)=new RichFile(file)
}
class RichFile(val f:File) {
def read()=Source.fromFile(f).mkString
}
object RichFile{
def main(args: Array[String]) {
val f=new File("E://words.txt")
//使用import导入隐式转换方法
import MyPredef._
//通过隐式转换,让File类具备了RichFile类中的方法
val content=f.read()
println(content)
}
}
喜欢就点赞评论+关注吧
感谢阅读,希望能帮助到大家,谢谢大家的支持!