Scala 範例程式 - 擴充運算 (extendsBuiltins)

原始程式:extendBuiltins.scala

/* Adding ! as a method on int's */
object extendBuiltins extends Application {
  def fact(n: Int): BigInt =
    if (n == 0) 1 else fact(n-1) * n
  class Factorizer(n: Int) {
    def ! = fact(n)
  }
  implicit def int2fact(n: Int) = new Factorizer(n)

  println("10! = " + (10!))
}

執行結果:

D:\Scala\code>scalac extendBuiltins.scala

D:\Scala\code>scala extendBuiltins
10! = 3628800
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License