scala - 隱式轉換和隱式參數

隱式轉換

package demo12

class Fraction() {

  private var n: Int = 0
  private var m: Int = 0

  //輔助構造器,每一個輔助構造器都必須以一個對先前已定義的其他輔助構造器或主構造器的調用開始
  def this(n: Int, m: Int) {
    this() //調用主構造器
    this.n = n
    this.m = m
  }

  def *(that: Fraction): Fraction = {
    Fraction(this.n * that.n, this.m * that.m)
  }

  override def toString() = {
    this.n + " " + this.m
  }
}

object Fraction {
  def apply(n: Int, m: Int) = {
    new Fraction(n, m)
  }
}

object C21_1 {
  // 定義隱式轉換函數
  implicit def int2Fraction(n: Int) = Fraction(n, 1)
  def main(args: Array[String]) {
    // 將調用int2Fraction,將整數3轉換成一個Fraction對象。
    val result = 3 * Fraction(4, 5)
    println(result)
  }
}

利用隱式轉換豐富現有類庫的功能

import java.io.File
import scala.io.Source


//隱式的增強File類的方法
class RichFile(val from: File) {
  def read = Source.fromFile(from.getPath).mkString
}

object RichFile {
  //隱式轉換方法
  implicit def file2RichFile(from: File) = new RichFile(from)

}

object ImplicitTransferDemo{
  def main(args: Array[String]): Unit = {
    //導入隱式轉換
    import RichFile._
    //import RichFile.file2RichFile
    println(new File("c://words.txt").read)

  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章