0

I'm still pretty new to Scala. I'm having trouble trying to append two Sequences together because the compiler is complaining about the type of the Seq. I would like to start with a Seq[String] var and replace it with the addition of two Seq[String]'s. In the REPL session below, we see that y :+ x is a Seq[Object], but why?

Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val x = Seq[String]("a")
x: Seq[String] = List(a)

scala> var y = Seq[String]("b")
y: Seq[String] = List(b)

scala> y = y :+ x
<console>:9: error: type mismatch;
 found   : Seq[Object]
 required: Seq[String]
       y = y :+ x
             ^

scala> val z = y :+ x
z: Seq[Object] = List(b, List(a))
harschware
  • 13,006
  • 17
  • 55
  • 87

1 Answers1

4

It's because the :+ operator expects a single item, not a sequence. So what you're trying to do is comparable to var y:List[String] = List("b", List("a")), which isn't valid. You can see this in the documentation of Seq, which shows the type of :+ to be A => Seq[A].

I think you probably want to use the ++ operator instead.

resueman
  • 10,572
  • 10
  • 31
  • 45
  • I should have known. I was looking at [The sequence traits Seq, IndexedSeq, and LinearSeq](http://www.scala-lang.org/docu/files/collections-api/collections_5.html) which says `x +: xs` `A new sequence that consists of x prepended to xs.` Since it didn't mention types I thought `:+` must be ok. – harschware Dec 04 '14 at 19:18