Scala Option Advanced example

I’ve been tinkering with mime types in a toy Scalatra file server so while maintain a file with all known mime types a common task is to figure out the extension of a given file name.

With a bit out-of-the-box thinking on capturing the extension but without using Options therefore open to failures:

def findExtension(s:String)=s.reverse.takeWhile(_!='.').reverse

Here’s how it looks while wrapping the string in the Option monad and performing type-safe operations on it before returning a Some or None of the extension:

scala> def findExtension(s:String)=
 Option(s) //wrap into Option
 .filter(_.exists(_=='.'))  //ignore files without a dot
 .map(_.reverse)  //out-of-the-box thinking
 .map(_.takeWhile(_!='.'))  //maybe could be done with some non-greedy advanced regex too
 .filter(_.trim.nonEmpty)  //take "" empty strings as None
 .map(_.reverse)  //reverse back
findExtension: (s: String)Option[String]

scala> findExtension("hi")
res128: Option[String] = None

scala> findExtension("h.io")
res129: Option[String] = Some(io)

scala> findExtension("www.github.io")
res130: Option[String] = Some(io)