Reputation: 53876
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 ?
Upvotes: 0
Views: 299
Reputation: 9820
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
}
Upvotes: 2