gpt4 book ai didi

scala - 为什么这个在参数中分配 val 的 Scala 代码可以工作?

转载 作者:行者123 更新时间:2023-12-03 06:50:20 25 4
gpt4 key购买 nike

object Main {

def main(args: Array[String])
{
val x = 10
print(x="Hello World")
print(x)
}
}

output : Hello World10

众所周知,在 Scala 中 val 无法重新分配或更改,但这里 x 更改为

Hello World

打印时。

最佳答案

解释有点出人意料:print 有一个名为 x 的参数。使用 x = ... 使用 named argument ,因此 print(x="Hello World")print("Hello World") 相同。

参见Scala Predef docsPredef.scala来源:

object Predef /*....*/ {

/*....*/
def print(x: Any) = Console.print(x)

/*....*/
}

注意:这已经在 Scala Internal mailing list 中讨论过:

Scala currently tries to be smart about treating "x = e" as a named argument or an assignment ... This can be surprising to the user ....

Proposal: we deprecate assignments in argument lists

还有exists an issue SI-8206为此,更改可能在 issue 426 中实现。对于 Scala 2.13。

您的代码在弃用后仍会编译,具有相同的含义。这一变化不会再被任何人(至少没有足够熟悉语言规范/实现的人)期望它被解释为赋值。

关于scala - 为什么这个在参数中分配 val 的 Scala 代码可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250423/

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