Scala 并行赋值仅在声明中

发布于 2024-11-03 01:38:15 字数 287 浏览 0 评论 0原文

有:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉城凉梦凉人心 2024-11-10 01:38:15

您可以在此处看到初始化变量时模式匹配的有限版本。请注意,这不仅适用于元组:

val a :: b = List(1,2,3)
println(a) //1
println(b) //List(2, 3)

此功能似乎是直接从 Haskell 借用的,您也可以使用模式进行初始化:

let (a,b) = getTuple 
in a*b

由于 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:

val a :: b = List(1,2,3)
println(a) //1
println(b) //List(2, 3)

This feature seems to be borrowed directly from Haskell, where you can use patterns for initialization as well:

let (a,b) = getTuple 
in a*b

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 a case, e.g. List((1,2),(3,4)).map{ case (a,b) => a*b }.

等风来 2024-11-10 01:38:15

我的怀疑是,如果变量名称元组左侧没有“var”或“val”,编译器会将元组视为元组。也就是说,您实际上是在尝试将值分配给 Tuple3 的实例而不是三个变量,这对编译器来说毫无意义。

顺便说一句,在您的示例中使用函数和各种数据类型是不相关的。这是一个更简单的例子:

scala> var ( i, j, k ) = ( 1, 2, 3 )
i: Int = 1
j: Int = 2
k: Int = 3

scala> ( i, j, k ) = ( 4, 5, 6 )
<console>:1: error: ';' expected but '=' found.
       ( i, j, k ) = ( 4, 5, 6 )
                   ^

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:

scala> var ( i, j, k ) = ( 1, 2, 3 )
i: Int = 1
j: Int = 2
k: Int = 3

scala> ( i, j, k ) = ( 4, 5, 6 )
<console>:1: error: ';' expected but '=' found.
       ( i, j, k ) = ( 4, 5, 6 )
                   ^
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文