Jwan622
Jwan622

Reputation: 11659

Checking if file path extension exists logic. Scala

I have a method that looks like this:

val extension = if (keepExtension) {
      if (!FilenameUtils.getExtension(path).isEmpty) s"${FilenameUtils.getExtension(path)}." else ""
    }
    else ""

Is there a better way to write this?

In short, sometimes I want files to keep their extension before zipping (so somefile.csv would become somefile.csv.zip) and if there is no file extension I want to just add the extension (so somefile becomes somefile.zip) and I want to handle the extra period correctly if there is or is not an extension.

Notice the period. I can't just write if (keepExtension) FilenameUtils.getExtension(path) else "". The tests would fail.

EDIT

This is what I needed:

val extension = if (keepExtension && !FilenameUtils.getExtension(path).isEmpty) s"${FilenameUtils.getExtension(path)}." else ""

Upvotes: 0

Views: 297

Answers (1)

Dennis Hunziker
Dennis Hunziker

Reputation: 1293

Edited as I missed the extension separator.

Isn't your actual aim then to just create the following?

val fileName = (if(!keepExtension) FilenameUtils.removeExtension(path) else path) + ".zip"

Maybe some more details on how you then plan to use that extension value you defined might help.

Upvotes: 1

Related Questions