1

How can i add an item using loop in ListBuffer of tuples using Scala? I have declared the List as:

val listV = new ListBuffer[(String,Int)]();

On adding item like this:

listV += ("a",1)

gives an error of : type mismatch as following

[error]  found   : String("a")

[error]  required: (String, Int)

[error]         listV += ("a",1)

[error]                   ^

[error] one error found

Any suggestions to resolve this ? Thanks in anticipation

1
  • 1
    Consider marking an answer as correct, so that this question doesn't remain unanswered. Commented Mar 20, 2015 at 14:12

3 Answers 3

8

+= is a method on ListBuffer, so the scala compiler thinks you're trying to pass two parameters to the += method. You need an extra set of parenthesis to emphasize that the tuple is a single element and not an invalid parameter list.

listV += (("a", 1))
Sign up to request clarification or add additional context in comments.

Comments

1

More parentheses. ("a",1) is interpreted as adding a String and an Int to listV.

scala> val listV = new ListBuffer[(String, Int)]
listV: scala.collection.mutable.ListBuffer[(String, Int)] = ListBuffer()

scala> listV += (("a", 1))
res0: listV.type = ListBuffer((a,1))

Comments

1

You can use this syntax which compiler can mix up with the function call:

listV += "a" -> 1

If you are more used to always having braces around Tuples this will also be interpreted correctly

listV += ("a" -> 1)

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.