1

I have the following array:

var as = Array.empty[Tuple2[Int, Int]]

I am adding an element to it like this:

var nElem = Tuple2(current, current)
as += nElem

current is a var of type Int

However, I am getting this error:

Solution.scala:51: error: type mismatch;
 found   : (Int, Int)
 required: String
                as += nElem

I don't understand why this is appearing. I haven't declared a String anywhere.

3 Answers 3

3

+= is the string concatenation operator. You are looking for :+ to append to an array. Note, that Array length is immutable, so :+=, will return a new array, with the nElem appended, and assign it to the as variable, the original array will stay unchanged (take this as a hint, that you are likely doing something in a suboptimal way).

Note, that if you find yourself using var, that is almost always a sign of a bad design in your code. Mutable objects and variables are considered really bad taste in functional programming. Sometimes, you can't get away without using them, but those are rare corner cases. Most of the time, you should not need mutability.

Also, do not use Tuple2. Just do Array.empty[(Int, Int)], nElem = (current, current) etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Array is not completely immutable, only it's length is immutable (as in Java). So effectively, you can neither append or remove, only replace current elements.
2

Use a :+= to modify the variable in place. However, remember this: Using both var and a mutable data structure at the same time (like Array) is a sign of really bad programming. Either is sometimes fine, though.

However, note that this operation is O(n), therefore pushing n elements like that is going to be slow, O(n²). Arrays are not meant to have elements pushed to back like that. You can alternatively use a var Vector instead and call .toArray() on it at the end or use a mutable val ArrayBuffer. However, prefer functional style of programming, unless it produces less readable code.

Also, avoid typing Tuple2 explicitly. Use Array.empty[(Int, Int)] and var nElem = (current, current).

Comments

1

The semantics of + are weird because of the automatic conversion to String in certain cases. To append to an array, use the :+ method:

as :+= nElem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.