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

4lex1v
  • 21,367
  • 6
  • 52
  • 86
malmling
  • 2,398
  • 4
  • 19
  • 33

2 Answers2

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.

Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129
  • 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! – malmling Sep 27 '13 at 11:19
1

Short foldLeft example:

sl.foldLeft(Seq[Map[Srting, String]]()){ (acc, item) =>  Map(/* map from item */) +: acc }
4lex1v
  • 21,367
  • 6
  • 52
  • 86