'why no tailOption in Scala?
Why is no tailOption in Scala, if there is headOption ?
This is an old question, found no answer on google.
Solution 1:[1]
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.
Solution 2:[2]
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
Solution 3:[3]
Actually, there is lastOption which does exactly what you want
Solution 4:[4]
You can use the following code.
s match {
case head :: tail => Option(tail)
case _ => None
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | shashwat |
| Solution 3 | remdezx |
| Solution 4 | xusliebana |
