The use of :_* in scala and operations such as :: , +:, :+, :::, +++ in scala

1. The use of _* in scala

Scala allows the last parameter of a function to be repeated. This allows users to pass variable-length parameter lists to functions. To declare a repeating parameter, put an asterisk after the parameter's type.

1. Calculate the sum of 1 to 4

def main(args: Array[String]): Unit = {

       val total = sum(1,2,3,4)
        println(total)

    }

    def sum(args: Int*) = {
        var result = 0
        for (arg <- args) result += arg
        result
    }

2. Use:_*

 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)
To achieve this function, you need to add a colon and a _* symbol after the array parameter. 
This way of writing tells the compiler to treat each element of arr as a parameter instead of passing it to the method as a single parameter. 
In the above code, you can use :_*
def main(args: Array[String]): Unit = {

       val total = sum(1 to 4:_*)
        println(total)


    }
    //变长参数
    def sum(args: Int*) = {
        var result = 0
        for (arg <- args) result += arg
        result
    }

3. :_* as a whole

:_* Taken as a whole, tell the compiler that you want a parameter to be treated as a sequence of parameters! For example, val s = sum(1 to 4:_*) treats 1 to 5 as a sequence of parameters.

https://shuqi.blog.csdn.net/article/details/113245405

Why does Scala's toSeq convert an immutable Set to a mutable ArrayBuffer? |

2. Operations in Scala:: , +:, :+, :::, +++, etc.

Beginners in Scala will definitely have some doubts about these operations: :: , +:, :+, :::, +++. Let’s summarize them today for your convenience.

/**
 * scala中的:: , +:, :+, :::, +++, 等操作;
 */
object listTest {
  def main(args: Array[String]): Unit = {
    val list = List(1,2,3)
    // :: 用于的是向队列的头部追加数据,产生新的列表, x::list,x就会添加到list的头部
    println(4 :: list)  //输出: List(4, 1, 2, 3)
    // .:: 这个是list的一个方法;作用和上面的一样,把元素添加到头部位置; list.::(x);
    println( list.:: (5)) //输出: List(5, 1, 2, 3)
    // :+ 用于在list尾部追加元素; list :+ x;
    println(list :+ 6)  //输出: List(1, 2, 3, 6)
    // +: 用于在list的头部添加元素;
    val list2 = "A"+:"B"+:Nil //Nil Nil是一个空的List,定义为List[Nothing]
    println(list2)  //输出: List(A, B)
    // ::: 用于连接两个List类型的集合 list ::: list2
    println(list ::: list2) //输出: List(1, 2, 3, A, B)
    // ++ 用于连接两个集合,list ++ list2
    println(list ++ list2) //输出: List(1, 2, 3, A, B)
  }
}

Guess you like

Origin blog.csdn.net/Alex_81D/article/details/129811641