MIME type mapping
I agree with @glowcoder. I believe that, at least in this particular case, it is better to have a MIME type mapping. Here is the Scala version:
val MimeTypesMapping = Map( ".pdf" -> "application/pdf", ".dxf" -> "application/dxf", ".jpg" -> "image/jpeg" ) def extension(fileName: String) = fileName substring (fileName lastIndexOf ".") def getMIMEType(document: String) = MimeTypesMapping get extension(document) getOrElse "application/octet-stream"
In addition, as Rex Kerr noted, you can add a default value directly to the display definition:
val MimeTypesMapping = Map( ".pdf" -> "application/pdf", ".dxf" -> "application/dxf", ".jpg" -> "image/jpeg" ) withDefaultValue "application/octet-stream"
and then use it like this: MimeTypesMapping(extension(document))
Pattern matching
If you don't like the first solution, you can use pattern matching instead:
def getMIMEType(document: String) = extension(document) match { case ".pdf" => "application/pdf" case ".dxf" => "application/dxf" case ".jpg" => "image/jpeg" case _ => "application/octet-stream" }
The advantage of this solution is that you can use more complex logic in conditions such as:
def getMIMEType(document: String) = extension(document) match { // ... case ".jpg" | ".jpeg" => "image/jpeg" // ... }
Comparison with custom extractor
There is also another way to use pattern matching. You can write your own extractor to expand the file, and then use it in match :
object Extension { def unapply(fileName: String): Option[String] = { val idx = fileName lastIndexOf "." if (idx != -1) Some(fileName substring idx) else None } } def getMIMEType(document: String) = document match { case Extension(".pdf") => "application/pdf" case Extension(".dxf") => "application/dxf" case Extension(".jpg") => "image/jpeg" case _ => "application/octet-stream" }
source share