递增并获得价值 [英] Incrementing and getting value

查看:62
本文介绍了递增并获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的scala问题.考虑以下内容.

Simple scala question. Consider the below.

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.

推荐答案

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

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

{ mycounter += 1; mycounter }

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

You can too do the trick using a closure (as function parameters are 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 ;)

这篇关于递增并获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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