Scala中的Varargs

Scala varargs (Scala varargs)

Varargs is the concept of providing a variable-length argument to a function. Scala programming language also provides this functionality in its programs.

Varargs是为函数提供变长参数的概念。 Scala编程语言还在其程序中提供了此功能。

In Scala, the last argument of the method can be of variable argument i.e. it can be repeated the multiple numbers of times in the parameter list of the method. In this function, the programmer can pass multiple arguments.

在Scala中,方法的最后一个参数可以是可变参数,即可以在方法的参数列表中重复多次。 在此函数中,程序员可以传递多个参数。

The varargs are stored as an array of the same data type i.e. array [data_type]. For example, if you use float as the data type of varargs, they are stored as array [float].

可变参数存储为具有相同数据类型的数组,即数组[data_type] 。 例如,如果使用float作为varargs的数据类型,则它们将存储为数组[float] 。

To make a method accept varargs, you need to place an asterisk (*) at last argument which will be made of variable length i.e. varargs.

为了使方法接受varargs,您需要在最后一个参数处加一个星号( * ),该参数将由可变长度(即varargs)组成

Syntax:

句法:

    def method_name (valarg_name : data_tpye *) : Int = { code }

Varargs are good to go when you do not know the number of arguments that a method will accept.

当您不知道某个方法将接受的参数数量时,最好使用Varargs

Example 1:

范例1:

object MyObject 
{ 
    def stringreturn(strings: String*) 
    { 
        strings.map(print) 
    }
    
    def main(args: Array[String]) 
    { 
        stringreturn("Hello! ", "Welcome ", "To ", "Include Help") 
    } 
} 

Output

输出量

Hello! Welcome To Include Help

Example 2:

范例2:

object MyObject 
{ 
    def avg(a: Int *) : Double =
    { 
        var result = 0 
        var count = 0
        
        for(arg <- a) 
        { 
            result += arg 
            count+= 1
        } 
        return result/count 
    }
    
    def main(args: Array[String]) 
    { 
        println("The average is: " + avg(543, 98, 123, 25, 323)); 
    } 
}

Output

输出量

The average is: 222.0


翻译自: https://www.includehelp.com/scala/varargs.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值