gpt4 book ai didi

scala 22 参数和更多参数 *

转载 作者:行者123 更新时间:2023-12-01 00:53:15 25 4
gpt4 key购买 nike

我们知道 Scala 不支持超过 22 个参数,但是如果我写这个

 def echo(args: String*) = for (arg <- args) println(arg)

我们可以使用超过 22 个参数来像这样调用这个函数。
echo("1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1")

但我认为这是一个数组。所以,它可以做到这一点,我试过这个
val a = Array[String]("1","2","3");echo(a)

这段代码肯定是错误的,所以这是我的第一个问题,为什么会发生这种情况?
而且,如果我尝试写这个
echo(a : _*)

对了,第二个问题是,这个符号'_*'是什么意思?我不能以其他方式使用此代码,例如 for()。那么, echo(a : _ *) 是正确的代码吗?

最佳答案

echo 函数被定义为采用可变数量的字符串参数。这实际上只是语法糖;编译器将插入必要的指令将参数包装在数组中,然后传递数组。因此该函数实际上只会在运行时接收一个参数。

您不能直接传递数组的原因是没有额外的编译器逻辑来自动确定字符串参数已经被包装。函数声明表明需要零个或多个字符串,参数实际上是一个数组,并导致编译器错误。

: _* 符号是额外的语法糖来解决这个问题;通过使用此语法,您向编译器表明您有意传递一个数组而不是可变数量的字符串参数。

关于scala 22 参数和更多参数 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com