package test_39 import scala.language.postfixOps //需求: 给整数添加一个功能,求阶乘 //5!=1*2*3*4*5 =120 object test3 { implicit class xxx(d:Int){ def ! : Int={ println("阶乘函数被调用",d) //写代码,完成1*2*3*...*d var result = 1 for (i <- 1 to d) { result *= i } result } } def main(args: Array[String]): Unit = { println(5.!) println(6!) // var i = 1 } }
结果是:
(阶乘函数被调用,5)
120
(阶乘函数被调用,6)
720