Scala对现有变量的多重赋值 [英] Scala multiple assignment to existing variable

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

问题描述

我可以做类似的事情

def f(): Tuple2[String, Long] = ...
val (a, b) = f()

如果变量已经存在呢?我在过滤器上运行相同的数据集,我不想链接它们(长名称等).这是我尝试过的,但它抱怨期待 ;而不是最后一行的 =:

What about if the variables are already existing? I'm running the same sets of data over filters and I don't want to chain them (long names and such). This is what I tried, but it complains about expecting ; instead of = on the last line:

var a = ...initialization for this data
var b = ...some other init
(a, b) = g(a, b) // error: expected ';' but found '='

有没有办法避免中间元组?

Is there a way to avoid an intermediary tuple?

推荐答案

正如 Alex 所指出的,简短的回答是否定的.你的代码发生了什么:当 ab 已经是当前作用域中的绑定变量时,(a, b) 意味着取 a 和 b 的值并从中构造一个元组."

As Alex pointed out, the short answer is no. What's going on with your code is this: when a and b are already bound variables in the current scope, (a, b) means "take the values of a and b and construct a tuple from them."

因此,

(a, b) = ...

相当于

(new Tuple2(a, b)) = ...

这显然不是你想要的(除了荒谬).

which is obviously not what you want (besides being nonsensical).

您想要的语法(一次分配给多个变量的能力)根本不存在.你甚至不能一次将相同的值分配给多个预先存在的变量(在许多其他语言中发现的通常语法a = b = ..."在Scala中不起作用.)我不要认为 vals 比 vars 得到优惠待遇是偶然的;它们几乎总是一个更好的主意.

The syntax you want (ability to assign to multiple variables at once) simply doesn't exist. You can't even assign the same value to multiple preexisting variables at once (the usual syntax "a = b = ..." that's found in many other languages doesn't work in Scala.) I don't think it's an accident that vals get preferential treatment over vars; they're almost always a better idea.

听起来所有这些都发生在某种循环内,并进行重复分配.这不是非常惯用的 Scala.我建议您尝试在程序中避免使用 vars 并以更实用的方式做事,使用 map、flatMap、filter、foldLeft 等.

It sounds like all of this is taking place inside of a loop of some kind, and doing repeated assignments. This is not very idiomatic Scala. I would recommend that you try to eliminate the usage of vars in your program and do things in a more functional way, using the likes of map, flatMap, filter, foldLeft, etc.

这篇关于Scala对现有变量的多重赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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