Scala 入门笔记

能丰富现有类库功能,增强类的方法

隐式转换函数:以implicit关键字声明并带有单个参数的函数

   其中用到了装饰模式,门面模式

package day04

import scala.io.Source

class RichFile(val file: String) {
  def read(): String = {
    Source.fromFile(file).mkString
  }
}

object RichFile {
  def main(args: Array[String]): Unit = {
    // 显示的实现read方式
//    val file = "C:/workspace/War-and-peace.txt"
//    val lines: String = new RichFile(file).read()
//
//    println(lines)


    // 隐式的实现方式
    import day04.MyPredef.fileToRichFile
    val file = "C:/workspace/War-and-peace.txt"
    val content = file.read()

    println(content)
  }
}

===========================
package day04

object MyPredef {
  implicit def fileToRichFile(file: String) = new RichFile(file)
}

  

原文地址:https://www.cnblogs.com/sunnystone85/p/11365047.html