10.2 利用隐式函数丰富现有的类库

如果需要用到的一个现有类库, 但是很不幸, 里面缺少一个我们需要的方法.

比如: 如果java.io.File 能有个方法直接读取文件就好了, 我们就可以像下面这样使用:

var content = new File("b.txt").read

在 Java 中我们只能给 Oracle 公司请愿来添加这个功能.

但是在 Scala 中, 我们可以定制一个丰富的类型来提供想要的功能.

package com.atguigu.day10

import java.io.File

import scala.io.Source

object ImplicitDemo1 {
  def main(args: Array[String]): Unit = {
    implicit def file2RichFile(from: File): RichFile = {
      new RichFile(from)
    }

    println()
    // File 对象被隐式的转换成了RichFile对象
    val rl: RichFile = new File(getClass.getClassLoader.getResource("a.txt").getPath)
    println(rl.read)
  }

}

class RichFile(val from: File) {
  def read = Source.fromFile(from.getPath).mkString
}

另外一个例子:


import java.time.LocalDate

class DateHelper(val day: Int) {
    def days(when: String) = {
        val today: LocalDate = LocalDate.now
        if (when == "ago") {
            today.minusDays(this.day)
        } else {
            today.plusDays(this.day)
        }
    }
}

object DateHelper {
    def main(args: Array[String]): Unit = {
        implicit def int2DateHelper(day: Int) = new DateHelper(day)

        val ago = "ago"
        val from_now = "from_now"
        val past = 2 days ago // 2.days(ago)
        val future = 5 days from_now // 5.days(from_now)

        println(past)
        println(future)

    }
}
Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-01-06 17:49:58

results matching ""

    No results matching ""