隐式转换

定义:

简单RichFile增加read方法:
  1. package com.billstudy.scala.implicits
  2. import java.io.File
  3. import scala.io.Source
  4. /**
  5. * Created by Bill on 2015-07-02 20:11
  6. * 原生的java.io.File没有直接read的方法,通过定义RichFile增强实现Read隐式函数进行增强
  7. * Email: LuckyBigBill@gmail.com
  8. */
  9. class RichFileBaseImplicit(f: File){
  10. def read = Source.fromFile(f).mkString
  11. }
  12. object RichFileBaseImplicitContent{
  13. implicit def file2RichFile(f: File) = new RichFileBaseImplicit(f)
  14. }
  15. object RichFileBaseImplicit{
  16. import RichFileBaseImplicitContent.file2RichFile
  17. def main(args: Array[String]) {
  18. val content = new File("F:/word.txt").read
  19. println(content)
  20. }
  21. }

(更多…)