Scala 并行赋值仅在声明中
有:
def f () = {
(1, "two", 3.0)
}
为什么可以
var (x, y, z) = f()
但不行
var i = 0
var j = "hello"
var k = 0.0
// use i, j, k
...
//then
(i, j, k) = f() // ; expected but = found
?
Having:
def f () = {
(1, "two", 3.0)
}
Why is it ok
var (x, y, z) = f()
but not
var i = 0
var j = "hello"
var k = 0.0
// use i, j, k
...
//then
(i, j, k) = f() // ; expected but = found
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在此处看到初始化变量时模式匹配的有限版本。请注意,这不仅适用于元组:
此功能似乎是直接从 Haskell 借用的,您也可以使用模式进行初始化:
由于 Haskell 没有可变数据,因此无法分配某些内容。
在 Scala 中,你可以做这样的事情,但我猜这被认为太混乱,或者可能太难实现。您始终可以像往常一样使用
match
表达式,并且通常您只需要一个case
,例如List((1,2),(3,4)) .map{ 案例 (a,b) => a*b}
。You see here a limited version of pattern matching when initializing variables. Note that this works not only for tuples:
This feature seems to be borrowed directly from Haskell, where you can use patterns for initialization as well:
As Haskell has no mutable data, there is no way to assign something.
In Scala you could do something like this, but I guess this was considered too confusing, or maybe too difficult to implement. You can always use a
match
expression as usual, and often you need just acase
, e.g.List((1,2),(3,4)).map{ case (a,b) => a*b }
.我的怀疑是,如果变量名称元组左侧没有“var”或“val”,编译器会将元组视为元组。也就是说,您实际上是在尝试将值分配给 Tuple3 的实例而不是三个变量,这对编译器来说毫无意义。
顺便说一句,在您的示例中使用函数和各种数据类型是不相关的。这是一个更简单的例子:
My suspicion would be that without the "var" or "val" to the left of the tuple of variable names, the compiler treats the tuple as a tuple. That is, you're really trying to assign a value to an instance of
Tuple3
and not to the three variables, and that makes no sense to the compiler.Incidentally, using a function and various datatypes in your example isn't relevant. Here's a simpler example: