pmkrefeld
pmkrefeld

Reputation: 195

Why is appending to a List in Scala returning other List type?

Since searching for :+ doesn't yield any results (thanks google!) I couldn't find any answer to my question:

Why is:

a :+ b

resulting in

List[Any]

if both 'a' and 'b' are of type

List[Int]

try it out yourself, following won't compile (Scala 2.11.6, Idea14):

object AAA extends App {
  val a: List[Int] = List[Int]()
  val b: List[Int] = List[Int]()

  val x: List[Int] = a :+ b
}

thx in advance

Upvotes: 1

Views: 49

Answers (1)

gzm0
gzm0

Reputation: 14842

:+ appends a single element to a List. So you are appending a List[Int] to a List[Int], resulting in something like (if a and b are both set to List(1, 2)):

List(1, 2, List(1, 2))

Scala calculates the most common type between the element type (Int) and the thing you append (List[Int]), which is Any.

You probably wanted to concatenate two lists:

val x: List[Int] = a ++ b

Upvotes: 6

Related Questions