0

This drives me crazy, I can't figure out why this gives me an error.

Here an example of my code:

var seqOfObjects:Seq[Map[String, String]] = Seq[Map[String, String]]()
for(item <- somelist) {
  seqOfObjects += Map(
     "objectid" -> item(0).toString,
     "category" -> item(1),
     "name" -> item(2),
     "url" -> item(3),
     "owneremail" -> item(4),
     "number" -> item(5).toString)
}

This gives me an error saying:

Type mismatch, expected: String, actual: Map[String, String]

But a Map[String, String] is exactly what I want to append into my Seq[Map[String, String]].

Why is it saying that my variable seqOfObjects expects a String??

Anyone have a clue? Thanks

2 Answers 2

3

a += b means a = a.+(b). See this answer.

There is no method + in Seq, so you can't use +=.

scala> Seq[Int]() + 1
<console>:8: error: type mismatch;
 found   : Int(1)
 required: String
              Seq[Int]() + 1
                           ^

required: String is from string concatenation. This behavior is inherited from Java:

scala> List(1, 2, 3) + "str"
res0: String = List(1, 2, 3)str

Actually method + here is from StringAdd wrapper. See implicit method Predef.any2stringadd.

You could use :+= or +:= instead of +=.

Default implementation of Seq is List, so you should use +: and +:= instead of :+ and :+=. See Performance Characteristics of scala collections.

You could also use List instead of Seq. There is :: method in List, so you can use ::=:

var listOfInts = List[Int]()
listOfInts ::= 1

You can rewrite your code without mutable variables using map:

val seqOfObjects =
  for(item <- somelist) // somelist.reverse to reverse order
    yield Map(...)

To reverse elements order you could use reverse method.

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

1 Comment

Ok I see, I didn't even think about the += since that wasnt the error. But it looks like it was :) Thanks @senia, this helps alot!
1

Short foldLeft example:

sl.foldLeft(Seq[Map[Srting, String]]()){ (acc, item) =>  Map(/* map from item */) +: acc }

1 Comment

thanks for you answer @Alexlv , I will look into this aswell. Looks intresting!

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.