scala 递增并获得价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14797547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:57:19  来源:igfitidea点击:

Incrementing and getting value

scala

提问by dublintech

Simple scala question. Consider the below.

简单的scala问题。考虑以下。

scala> var mycounter: Int = 0;
mycounter: Int = 0

scala> mycounter += 1

scala> mycounter
res1: Int = 1

In the second statement I increment my counter. But nothing is returned. How do I increment and return something in one statement.

在第二个语句中,我增加了我的计数器。但什么也没有返回。如何在一个语句中增加和返回某些内容。

回答by Alois Cochard

Using '+=' return Unit, so you should do:

使用 '+='返回 Unit,所以你应该这样做:

{ mycounter += 1; mycounter }

You can too do the trick using a closure (as function parameters are val):

你也可以使用闭包来完成这个技巧(因为函数参数是 val):

scala> var x = 1
x: Int = 1

scala> def f(y: Int) = { x += y; x}
f: (y: Int)Int

scala> f(1)
res5: Int = 2

scala> f(5)
res6: Int = 7

scala> x
res7: Int = 7

BTW, you might consider using an immutable value instead, and embrace this programming style, then all your statements will return something ;)

顺便说一句,您可能会考虑使用不可变值,并采用这种编程风格,然后您的所有语句都会返回一些内容;)

回答by huynhjl

Sometimes I do this:

有时我这样做:

val nextId = { var i = 0; () => { i += 1; i} }
println(nextId())                               //> 1
println(nextId())                               //> 2

Might not work for you if you need sometime to access the value withoutincrementing.

如果您需要在增加的情况下访问该值,则可能不适合您。

回答by EECOLOR

Assignment is an expression that is evaluated to Unit. Reasoning behind it can be found here: What is the motivation for Scala assignment evaluating to Unit rather than the value assigned?

赋值是一个计算为 Unit 的表达式。其背后的推理可以在这里找到:Scala 赋值评估 Unit 而不是赋值的动机是什么?

In Scala this is usually not a problem because there probably is a different construct for the problem you are solving.

在 Scala 中,这通常不是问题,因为您正在解决的问题可能有不同的构造。

I don't know your exact use case, but if you want to use the incrementation it might be in the following form:

我不知道您的确切用例,但如果您想使用增量,它可能采用以下形式:

(1 to 10).foreach { i => 
  // do something with i
}