5

简单的斯卡拉问题。考虑以下。

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

scala> mycounter += 1

scala> mycounter
res1: Int = 1

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

4

3 回答 3

9

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

{ mycounter += 1; mycounter }

你也可以使用闭包来完成这个技巧(因为函数参数是 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

顺便说一句,您可能会考虑改用不可变值,并采用这种编程风格,那么您的所有语句都会返回一些东西;)

于 2013-02-10T12:18:11.607 回答
7

有时我会这样做:

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

如果您需要某个时间在不增加的情况下访问该值,则可能对您不起作用。

于 2013-02-10T15:12:00.690 回答
1

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?

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

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
}
于 2013-02-10T12:33:50.320 回答