bsky
bsky

Reputation: 20242

Scala type mismatch when adding an element to an array

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.

Upvotes: 1

Views: 709

Answers (3)

Dima
Dima

Reputation: 40510

+= 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.

Upvotes: 3

Rok Kralj
Rok Kralj

Reputation: 48775

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).

Upvotes: 2

user1804599
user1804599

Reputation:

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

Upvotes: 1

Related Questions