Scala Set different operations

53 views Asked by At

So here is my code snippet:

 val check = collection.mutable.Set[String]()
    if (check.isEmpty) {
      println("There is no transfer data available yet, please use the 'load' command to initialize the application!")
    }
    val userSelection = scala.io.StdIn.readLine("Enter your command or type 'help' for more information:")
    val loadCommand = """^(?:load)\s+(.*)$""".r
    userSelection match {
        case loadCommand(fileName) => check add fileName ;print(check);val l= loadOperation(fileName);println(l.length); if (check.contains(fileName)){
          programSelector()

        }else{ loadOperation(fileName)}

So first of all I have an input with the match and one case is the "load" input. Now my program is able to load different .csv files and store it to a List. However I want my program whenever it loads a new .csv file to check if it was loaded previously. If it was loaded before, it should not be loaded twice!! So i thought it could work with checking with an Set but it always overwrites my previous fileName entry...

1

There are 1 answers

5
bjfletcher On BEST ANSWER

Your set operations are fine. The issue is the check add fileName straight after case loadCommand(fileName) should be in the else block. (One of those "d'oh" moments that we have now and then!?) :)

Update

Code

val check = collection.mutable.Set[String]()
def process(userSelection: String): String = {
  val loadCommand = """^(?:load)\s+(.*)$""".r
  userSelection match {
    case loadCommand(fileName) =>
      if (check.contains(fileName))
        s"Already processed $fileName"
      else {
        check add fileName
        s"Process $fileName"
      }
    case _ =>
      "User selection not recognised"
  }
}

process("load 2013Q1.csv")
process("load 2013Q2.csv")
process("load 2013Q1.csv")

Output

res1: String = Process 2013Q1.csv
res2: String = Process 2013Q2.csv
res3: String = Already processed 2013Q1.csv