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 ?

2
  • 1
    Nothing involving randomUUID is going to be pure... Commented Jul 18, 2015 at 10:35
  • 1
    Nothing being random is going to be functionally pure if I remember correctly. Commented Jul 18, 2015 at 11:40

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.