Search code examples
scala

set increment using flatMap


I have a mutuable set and assigning the values to it from input

var set = scala.collection.mutable.Set[Int]() set ++= (in.readLine().split(" ").map(_.toInt))

Input:
1 5

Actual Output:
1,5

Required Output:
1,2,3,4,5

If have used flatMap with condition, but got error. How to achieve this with flatMap


Solution

  • I assume you have always a String like '2 5' as Input:

    The solution could look like:

    def toSeq(value: String): Seq[Int] = {
      value.split(" ")
      .map(_.toInt).toList match {
        case x1::x2::_ => x1 to x2
        case other => Nil// handle Exception
      }
    }
    println(toSeq("1 5").toList)
    

    Be aware that the input is not validated!