1.計算1到4的和
1 def main(args: Array[String]): Unit = { 2 3 val total = sum(1,2,3,4) 4 println(total) 5 6 } 7 8 def sum(args: Int*) = { 9 var result = 0 10 for (arg <- args) result += arg 11 result 12 }
2.使用:_*
def main(args: Array[String]): Unit = { val total = sum(1 to 5) println(total) } def sum(args: Int*) = { var result = 0 for (arg <- args) result += arg result } 報錯是: Error:(4, 26) type mismatch; found : scala.collection.immutable.Range.Inclusive required: Int val total = sum(1 to 5)
在上述代碼中,可以使用:_*
1 def main(args: Array[String]): Unit = { 2 3 val total = sum(1 to 4:_*) 4 println(total) 5 6 7 } 8 //變長參數 9 def sum(args: Int*) = { 10 var result = 0 11 for (arg <- args) result += arg 12 result 13 }
3. :_*作為一個整體,告訴編譯器你希望將某個參數當作參數序列處理!例如val s = sum(1 to 4:_*)就是將1 to 5當作參數序列處理。