Beginner Question regarding ArrayBuffer

Hello everyone,

I’ve got a quick question regarding a code I have to write. A brief description: I have to write a code about a ticket machine which will also count the money inserted and eventually return it to the customer, if he decides to cancel the process.

For the money inserted, I created a simple Array:
val money = Array(0.1, 0.2, 0.5, 1, 2, 5)

I use this Array to detect every kind of money which isn’t valid for the machine.

Furthermore, I created an empty ArrayBuffer to count all the pieces of money thrown inside:
var moneythrownin = ArrayBuffer()

And last bot not least, I have got a function to stock the type of coin tossed into the machine:
coininserted = StdIn.readLine("Please insert your money - Type 1 for 1€, etc.)

So, my problem is, that I wanted to write underneath this whole thing, that every “coin inserted” is added to the empty ArrayBuffer. So I wrote:
MoneyThrownIn += CoinInserted

The code doesn’t work, because Scala isn’t accepting my “+=” - can someone please help me?

Thanks in advance

Can you show your code more exactly, and what error you’re getting? The code you have here isn’t possible, so I think you’re transcribing by hand, and the details might matter. If you put a line containing just three backticks (```) and nothing else, before and after the code, it will display more nicely.

That said – if you’re saying:

var moneythrownin = ArrayBuffer()

Then I believe you are creating an ArrayBuffer that you can’t actually put anything into, because you haven’t said what type it is. You probably need to say:

val moneythrownin = ArrayBuffer[String]()

to say that this is an ArrayBuffer of Strings.

Also, note that moneythrownin should probably be a val, not a var. The ArrayBuffer is itself mutable – that is, you can change the values inside of it; you don’t need a var to do that. You would only need it to be a var if you intended to create different ArrayBuffers and assign them to moneythrownin, which probably isn’t what you intend.

(In general, vars are unusual in idiomatic Scala – you should always use val unless you have a specific reason to use a var.)