Scala repeated方法参数

Scala repeated方法参数

在Scala中,支持 repeated方法参数 ,当我们不知道一个方法需要多少个参数时,这很有帮助。
重要的一点是,Scala的这一属性在向一个方法定义传递无限的参数时得到了利用。

  • 有重复参数的方法,每个参数的类型都是一样的。
  • 一个重复参数总是定义的方法的最后一个参数。
  • 我们定义的方法,只能有一个参数作为重复参数。

例子。

// Scala program of repeated 
// parameters
  
// Creating object
object repeated
{
  
    // Main method
    def main(args: Array[String])
    {
  
        // Creating a method with
        // repeated parameters
        def add(x: Int*)
        : Int =
        {
  
            // Applying 'fold' method to 
            // perform binary operation
            x.fold(0)(_+_)
      
        }
  
        // Displays Addition
        println(add(2, 3, 5, 9, 6, 10, 11, 12))
    }
}

输出。

58

为了增加任何数量的额外参数,我们需要在被使用的参数类型后面加上*标记。
一些更多的重复参数的例子。

  • 可以在重复参数方法中传递一个数组。

示例:

// Scala program of repeated 
// parameters
  
// Creating object
object arr
{
  
    // Main method
    def main(args: Array[String])
    {
  
        // Creating a method with
        // repeated parameters
        def mul(x: Int*)
        : Int =
        {
  
            // Applying 'product' method to 
            // perform multiplication
            x.product
      
        }
  
        // Displays product
        println(mul(Array(7, 3, 2, 10): _*))
    }
}

输出:

420

为了在定义的方法中传递一个数组,我们需要在传递数组中的值之后加上冒号,即:和*标记。

  • 一个例子表明,重复参数总是定义方法的最后一个参数。

示例:

// Scala program of repeated 
// parameters
  
// Creating object
object str
{
  
    // Main method
    def main(args: Array[String])
    {
  
        // Creating a method with
        // repeated parameters
        def show(x: String, y: Any*) =
        {
      
            // using 'mkString' method to
            // convert a collection to a
            // string with a separator
            "%s is a %s".format(x, y.mkString("_"))
        }
  
        // Displays string 
        println(show("GeeksforGeeks", "Computer",
                            "Sciecne", "Portal"))
    }
}

输出:

GeeksforGeeks is a Computer_Sciecne_Portal

这里,format用于格式化字符串。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程