Getting the Scala function vararg

Scala vararg 

In Scala sometimes we need to function as a variable number of parameters defined form, at this time can use variable length parameter defined function.

 

def sum(nums: Int*) = {

  was res = 0

  for (num <- nums) res += num

  res

}

sum(1, 2, 3, 4, 5)

 

Using variable length parameter sequence calls

If you want to have in a sequence of variable-length argument function called directly, it is wrong. For example Val S = SUM (. 1 to. 5) .

In this case requires the use of Scala special syntax parameters are defined as a sequence, so Scala interpreter to recognize. This syntax is very useful! Must be a good idea, in spark a lot of use to the source code.

 '_' Optional elements

val s = sum(1 to 5: _*)

Case: Using a recursive function for an accumulation

def sum2(nums: Int*): Int = {

  if (nums.length == 0) 0

  else nums.head + sum2(nums.tail: _*)

}

 

Guess you like

Origin www.cnblogs.com/YuanWeiBlogger/p/11415528.html