Stas S Stas S - 1 year ago 213
Scala Question

Scala - delete file if exist, the Scala way

How to nicely delete file in Scala, "the Scala way"?

For example, i can use something like this, very Java style:

private def deleteFile(path: String) = {
val fileTemp = new File(path)
if (fileTemp.exists) {

How would it be implemented in Scala, in a more functional syntax?

Answer Source

You can't get rid of side effects while doing IO-operations, so no good functional ways here. All functional stuff is actually ends when you start to interact with user/devices directly, no monad can help you to do one external side-effect; however, you can describe (wrap) sequential side-effects using IO-like Monads.

Talking about your example, monad-restyled code may look like:

implicit class FileMonads(f: File) {
  def check = if (f.exists) Some(f) else None //returns "Maybe" monad
  def remove = if (f.delete()) Some(f) else None //returns "Maybe" monad

for {
  foundFile <- new File(path).check
  deletedFile <- foundFile.remove
} yield deletedFile

res11: Option[] = None

But that's too verbose without any real advantages if you just want to delete one file. More than that, fileTemp.exists check has no sense and actually isn't reliable (as @Eduardo pointed out). So, even in Scala the best way I know is FileUtils.deleteQuietly:

  FileUtils.deleteQuietly(new File(path))

Or even

  new File(path).delete()

It won't throw an exception for non-existent file - just return false.

If you really want something more Scala-way - look at for example:

  val file = uri"file:///home/work/garbage"

Or scala-io. More info: How to do File creation and manipulation in functional style?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download