在 Scala 中一次分配多个变量 [英] Assign multiple variables at once in scala

查看:45
本文介绍了在 Scala 中一次分配多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

val text = "some text goes here"
val (first, rest) = text.splitAt(4)
println(first + " *" + rest)

效果很好.

不过,我想有两种情况,在外面定义first"和rest",像这样:

However, I want to have two cases, defining "first" and "rest" outside, like this:

val text = "some text goes here"
var (first, rest) = ("", "")
if (text.contains("z")) {
  (first, rest) = text.splitAt(4)
} else {
  (first, rest) = text.splitAt(7)
}
println(first + " *" + rest)

但这给了我一个错误:

scala>      | <console>:2: error: ';' expected but '=' found.
         (first, rest) = text.splitAt(4)

为什么执行 (first, rest) = text.splitAt(4) 而不是执行 val (first, rest) = text.splitAt(4) 是错误的?我该怎么办?

Why is it an error to do (first, rest) = text.splitAt(4) but not to do val (first, rest) = text.splitAt(4)? And what can I do?

无法重新分配 val,已更改为 var.同样的错误

Can't re-assign val, changed to var. Same error

推荐答案

Serj 的回答提供了一种更好的写作方式,但是要回答关于为什么第二个版本不起作用的问题,您可以转到Scala 规范,它区分了变量定义赋值.

The answer by Serj gives a better way of writing this, but for an answer to your question about why your second version doesn't work, you can go to the Scala specification, which makes a distinction between variable definitions and assignments.

来自4.2 变量声明和定义":

From "4.2 Variable Declarations and Definitions":

变量定义也可以有一个模式(第 8.1 节)作为左手边.一个变量定义 var p = e 其中 p 是一个除了简单名称或名称后跟冒号和类型以与值定义相同的方式(第 4.1 节)扩展 val p= e,除了 p 中的自由名称是作为可变变量引入的,而不是值.

Variable definitions can alternatively have a pattern (§8.1) as left-hand side. A variable definition var p = e where p is a pattern other than a simple name or a name followed by a colon and a type is expanded in the same way (§4.1) as a value definition val p = e, except that the free names in p are introduced as mutable variables, not values.

来自6.15 作业":

From "6.15 Assignments":

对简单变量 x = e 赋值的解释取决于关于 x 的定义.如果 x 表示可变变量,则赋值将 x 的当前值更改为对表达式 e 求值.

The interpretation of an assignment to a simple variable x = e depends on the definition of x. If x denotes a mutable variable, then the assignment changes the current value of x to be the result of evaluating the expression e.

(first, rest) 这里是一个模式,不是一个简单的变量,所以它在变量定义中起作用,但在赋值中不起作用.

(first, rest) here is a pattern, not a simple variable, so it works in the variable definition but not in the assignment.

这篇关于在 Scala 中一次分配多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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