隱式轉換
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]) {
val result = 3 * Fraction(4, 5)
println(result)
}
}
利用隱式轉換豐富現有類庫的功能
import java.io.File
import scala.io.Source
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._
println(new File("c://words.txt").read)
}
}