Home > OS >  How to push or append a Option[Long] to Seq[Long] if the option is defined?
How to push or append a Option[Long] to Seq[Long] if the option is defined?

Time:10-09

I'm trying to use the code below to append items into a Seq, I realize in scala that a Seq may be immutable, so this might not work as I expect.

object Main extends App {
  val x: Long = 122222222
  val y: Option[Long] = Some(133333333)
  // val y: Option[Long] = None
  val z: Option[Long] = Some(144444444)

  val users: Seq[Long] = Seq(x)

  if (y.isDefined) users.appended(y)
  if (z.isDefined) users.appended(z)
  
  println(users)
  println(users.length)
}

Thanks!

CodePudding user response:

This is probably the simplest solution:

val users: Seq[Long] = Seq(x)    y.toSeq    z.toSeq

toSeq will turn None into Nil and Some(x) into List(x), and then you can just concatenate the lists.

CodePudding user response:

appended(value) returns a new sequence consisting of all elements of this sequence followed by value. . It doesnt change in-place.

If you want to keep the way your code looks like, you can do

    var users: Seq[Long] = Seq(x) // change val to var

    if (y.isDefined) users = users.appended(y.get)
    if (z.isDefined) users = users.appended(z.get)

Note: This

    if (y.isDefined) users = users.appended(y.get)
    if (z.isDefined) users = users.appended(z.get)

could be changed to

    y.foreach(users : = _)
    z.foreach(users : = _)
  • Related