对现有变量进行Scala多重分配 [英] Scala multiple assignment to existing variable

查看:70
本文介绍了对现有变量进行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指出的,简短的答案是否".您的代码是这样的:当 a b 在当前范围内已经是绑定变量时,(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中不起作用.) val而不是var享受优惠待遇不是偶然的事;他们几乎总是一个更好的主意.

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.我建议您尝试消除程序中var的使用,并使用诸如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天全站免登陆