Question

i wanna have a result-Sequence with a Triple of (String, Int, Int) like this:

var all_info: Seq[(String, Int, Int)] = null

now that i try adding elements to my Seq as followed:

  if (all_info == null) {
    all_info = Seq((name, id, count))
  } else {
    all_info :+ (name, id, count)
  }

and print them

    Console.println(all_info.mkString)

Unfortunately, the printed result is only the first triple that is added by the if-clause and basically intializes a new Seq, since it's been just "null" before. All following triples which are supposed to be added to the Seq in the else-clause are not. I also tried different methods like "++" which won't work either ("too many arguments")

Can't really figure out what I'm doing wrong here.

Thanks for any help in advance! Greetings.

Was it helpful?

Solution

First of all instead of using nulls you would be better using an empty collection. Next use :+= so the result of :+ would not be thrown away — :+ produces a new collection as the result instead of modifying the existing one. The final code would look like

var all_info: Seq[(String, Int, Int)] = Seq.empty
all_info :+= (name, id, count)

As you can see, now you don't need ifs and code should work fine.

OTHER TIPS

Method :+ creates new collection and leaves your original collection untouched.

You should use method +=. If there is no method += in all_info compiler will treat all_info += (name, id, count) as all_info = all_info + (name, id, count).

On the contrary, if you'll change the type of all_info to some mutable collection, you'll get method += in it, so your code will work as expected: method += on mutable collections changes target collection.

Note that there is no method :+= in mutable collections, so you'll get all_info = all_info :+ (name, id, count) even for mutable collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top