加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

当Row确实接受varargs时,为什么Scala编译器会因“no’:_ *’这

发布时间:2020-12-16 18:21:26 所属栏目:安全 来源:网络整理
导读:我想在不知道其编号的情况下创建一个包含多个参数的Row.我在 Scala中写了这样的东西: def customRow(balance: Int,globalGrade: Int,indicators: Double*): Row = { Row( balance,globalGrade,indicators:_* )} 在Spark GitHub,Row对象似乎接受:_ *表示法
我想在不知道其编号的情况下创建一个包含多个参数的Row.我在 Scala中写了这样的东西:

def customRow(balance: Int,globalGrade: Int,indicators: Double*): Row = {
    Row(
      balance,globalGrade,indicators:_*
    )
}

在Spark GitHub,Row对象似乎接受:_ *表示法考虑其apply方法:

def apply(values: Any*): Row = new GenericRow(values.toArray)

但是在编译时,似乎不允许这样做:

Error:(212,19) no ': _*' annotation allowed here
(such annotations are only allowed in arguments to *-parameters)
        indicators:_*

我错过了什么?

解决方法

这个最小的例子可以更好地解释为什么不允许你想做的事情:

def f(a: Int,b: Int,c: Int,rest: Int*) = a + b + c + rest.sum

val ns = List(99,88,77)

f(11,22,33,44,ns:_*) // Illegal
f(11,ns:_*) // Legal
f(11,ns:_*) // Illegal

基本上,您只能使用:_ *语法直接传递序列作为vararg参数,但它是全有或全无.序列的项不在simple参数和vararg参数之间共享,并且vararg参数不能从简单参数和提供的序列中收集值.

在你的情况下,你试图调用Row,好像它有两个简单的参数,然后是一个vararg,但事实并非如此.当您自己创建序列时,您将使其正确适合签名.

请注意,在动态类型编程语言中,这通常不是问题.例如,在Python中:

>>> def f(a,b,c,*rest):
    return a + b + c + sum(rest)

>>> ns = [99,77]
>>> f(11,*ns)
374
>>> f(11,*ns)
330
>>> f(11,*ns)
297

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读