why no tailOption in Scala?

Actually, there is lastOption which does exactly what you want


I never though of this before, it's kind of intriguing why tailOption in not part of the standard library. I don't know about why it is not there, but we can definitely extend the functionality by catching the error thrown by tail of empty list.

def getOption[A](a: => A) = {
   try{ Some(a) }
   catch { case e: Exception => None }
}

getOption(List(1,2,3).tail) // Some(3)
getOption(Nil.tail)  // None

There is no need for tailOption. If you want a function behaving like tail. but returning empty collection when used on empty collection, you can use drop(1). I often use this when I want to handle empty collection gracefully when creating a list of pairs:

s zip s.drop(1)

If you want None on empty collection and Some(tail) on non-empty one, you can use:

s.headOption.map(_ => s.tail)

or (if you do not mind exception to be thrown and captured, which may be a bit slower):

Try {s.tail}.toOption

I can hardly imagine a reasonable use case for the other options, though.

Tags:

Scala