Scala in _ * Application

Extension brother code found in many places have used the: _ *, explore what happens today.

1. vararg 
example defines a method of variable length parameter sum, and then calculates 1-5, can be written as

  1.  
    scala> def sum(args: Int*) = {
  2.  
    | was result = 0
  3.  
    | for (arg <- args) result += arg
  4.  
    | result
  5.  
    | }
  6.  
    sum: (args: Int*)Int
  7.  
     
  8.  
    scala> val s = sum(1,2,3,4,5)
  9.  
    s: Int = 15

But if you use this way will error

  1.  
    scala> val s = sum( 1 to 5)
  2.  
    <console>: 12: error: type mismatch;
  3.  
    found : scala.collection.immutable.Range.Inclusive
  4.  
    required: Int
  5.  
    val s = sum( 1 to 5)
  6.  
    ^

In this case must be written on the back: 1 to 5 _ * The parameter sequence converted to

  1.  
    scala> val s = sum( to 5: _*)
  2.  
    s:  Int = 15
2. Variable declaration mode 

For example, the following code arr respectively in the first and second values ​​into first and second

scala> val arr = Array(1,2,3,4,5)
arr: Array[Int] = Array(1, 2, 3, 4, 5)

scala> val Array(1, 2, _*) = arr

scala> val Array(first, second, _*) = arr
first: Int = 1
second: Int = 2

 

Project code

addColumns.foreach(column => {

  if (column.udf != null && column.inputColumns != null) {
result = result.withColumn(column.name, column.udf(column.inputColumns.map(col): _*))
} else if (column.expression != null) {
result = result.withColumn(column.name, expr(column.expression))
}
}
)
inputColumns是一个List,
inputColumns.map (col): _ * flattened into a sequence parameter passed to a function udf

Guess you like

Origin www.cnblogs.com/muliti-hu/p/11280873.html