0

Below is code I wrote to generate a random String (to be used for filename) :

import scala.collection.mutable.ListBuffer

object FileName{

  var currentFileNameList: ListBuffer[String] = new ListBuffer

  def getFileName(): String = {
    var fileName = java.util.UUID.randomUUID().toString();

    while (true) {
      if (!currentFileNameList.contains(fileName)) {
        currentFileNameList = currentFileNameList :+ fileName
        return fileName
      } else {
        fileName = java.util.UUID.randomUUID().toString();
      }
    }

    throw new RuntimeException("Error - filename not generated")
  }

}

The exception throw new RuntimeException("Error - filename not generated") should never be thrown but is required as I need to return type String. What is Scala compiler not complaining that im throwing a RuntimeException instead of returning String ?

Is there functional equivalent (no vars) of re-writing above code ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752

1 Answers1

2

The result type of throwing an exception in Scala is Nothing which is the bottom type and thus can be used where (in your case) a String is expected.

The chance of UUID collisions is very small (see this question and wikipedia), but if you really want to check for file name collisions in a more functional matter, you could use a tail recursive function.

def randomFileName(existing: List[String]) : String = {
  val uuid = java.util.UUID.randomUUID.toString
  if (existing.contains(uuid)) randomFileName(existing)
  else uuid
}
Community
  • 1
  • 1
Peter Neyens
  • 9,770
  • 27
  • 33
  • same String could be generated by your method randomFileName as multiple calls to randomFileName will re-initialize List existing, so do not have history of created uuid's. – blue-sky Jul 18 '15 at 11:29
  • If you have created a new file, add the new filename to a list of existing file names and pass that list the next time you call `randomFileName`. – Peter Neyens Jul 18 '15 at 11:34