元组参数声明和赋值奇怪 [英] Tuple parameter declaration and assignment oddity

查看:43
本文介绍了元组参数声明和赋值奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以按如下方式分配元组:

I can assign a tuple as follows:

var (min, max) = (1, 2)

但我不能按如下方式重新分配

(min, max) = (1, 3) //compiler error: ';' expected but '=' found

相反,我似乎必须这样做:

Instead I seem to have to do:

min = 1
max = 3

为什么后者有效而前者无效?

Why does the latter work whereas the former does not?

推荐答案

好吧,我想是因为它是那样指定的.

Well, because it was spec'ed that way, I suppose.

这个,元组分配,是模式匹配的一个例子.模式匹配发生在我记得的三个地方:

This, the tuple assignment, is an example of pattern matching. Pattern matching happens in three places that I recall of:

var PATTERN = ... // or val

for (PATTERN <- ...) ...

case PATTERN => ...

所以所有这些情况都有效:

So all these cases work:

val l = List((1,'a'), (2,'b'), (3,'c'))
var (n, c) = l(0)
for ((n, c) <- l) println(n+": "+c)
l(1) match {
  case (n, c) => println(n+": "+c)
}

现在,以最后一个例子为例,使用 case 的例子.请注意,该示例中的 nc 不是相同的 nc定义得早一点.模式匹配会为标识符nc赋值,这将影响case<的escope的先前定义/code> 语句.同样的事情发生在 for 示例中,它没有改变之前定义的 nc.

Now, take the last example, the one using case. Note that n and c in that example are not the same n and c defined a bit earlier. The pattern match will assign values to new identifiers n and c, which will shadow the previous definition for the escope of the case statement. The same thing happened on the for example, which did not change n and c previously defined.

现在,您想要发生的是覆盖以前的值,而不是为新标识符分配新值.这不是模式匹配的工作方式,这意味着实现它需要一个全新的规则.由于 Scala 温和地促使人们走向不变性,我认为他们没有创建新规则来处理这个问题并不是没有道理的.

Now, what you want to happen is to overwrite the previous value, instead of assign new values to new identifiers. That's not how pattern matching works, which means making it happen would entail an entirely new rule. Since Scala gently prods people towards immutability, I suppose it's not unreasonable they did not create a new rule just to handle this.

这篇关于元组参数声明和赋值奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆