Search code examples
listscalaimmutabilitymutableprepend

Scala adding immutable list to mutable one


I am trying to add some user input Strings to an immutable List with tail recursion and then add this immutable List to a MutableList which is defined. Somehow this immutable List isn't getting prepended to my MutableList. Why is that so?

EDIT: Updated the code. Now its working!

val list = scala.collection.mutable.MutableList[String]()

  def exerciseSelector() {
    val user = scala.io.StdIn.readLine("go:")
    user match {
      case "add" => val tempList = scanInput(List[String]())
                    if (!tempList.isEmpty) list ++= tempList.get ; exerciseSelector()
      case "print" => println(list)
      case "exit" => sys.exit()
    }
  }

    def scanInput(acc: List[String]): Option[List[String]] = {
    val input = scala.io.StdIn.readLine("User input:")
    input match {
    case "stop" => Option(acc)
    case input: String => scanInput(input :: acc)
  }
}

exerciseSelector()

Solution

  • You have two mutually-recursive functions exerciseSelector and scanInput, which will only ever result in list being updated if scanInput returns, which ultimately can only happen after an input of "exit", which calls sys.exit(), quitting altogether before the return from scanInput can happen, and so before list ever gets updated.

    Any input of "print" will be printing out an empty list, as list never gets a chance to be updated without sys.exit() being called first.

    Depending on what exactly you are trying to achieve, I suspect just dropping out the co-recursive call to exerciseSelector() on receiving a "stop" input will fix your code (or get you a lot further towards your intended result).