is it possible to change this if-else-construct in a more functional style of Scala?
def getMIMEType(document: String): String = {
if (document.endsWith(".pdf")) {
return "application/pdf"
} else if (document.endsWith(".dxf")) {
return "application/dxf"
} else if (document.endsWith(".jpg")) {
return "image/jpeg"
} else return "application/octet-stream"
}
I tried to use pattern matching, but it doesn’t work. So I be curious for a good solution.
MIME-Type mapping
I agree with @glowcoder. I find that at least in this particular case it’s better to have MIME-Types mapping. Here is a Scala version:
Also, as Rex Kerr noted, you can add default value directly to the mapping definition:
and then use it like this:
MimeTypesMapping(extension(document))Pattern Matching
If you don’t like first solution, then you can use pattern matching instead:
Advantage of this solution is that you can can more sophisticated logic in the conditions like for example:
Pattern Matching with Custom Extractor
There is also another way to use pattern matching. You can write your own extractor for the file extension an then use it in
match: