Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala's indexOf (in List etc) return Int instead of Option[Int]?

I want to write really nice looking idiomatic Scala code list indexOf foo getOrElse Int.MaxValue but now I have to settle for idiotic Java looking code val result = list indexOf foo; if (result < 0) Int.MaxValue else result. Is there a good reason that indexOf in Scala returns Int instead of Option[Int]

like image 414
pathikrit Avatar asked Aug 22 '14 21:08

pathikrit


1 Answers

It's for compatibility with Java and for speed. You'd have to double-box the answer (first in java.lang.Integer then Option) instead of just returning a negative number. This can take on the order of ten times longer.

You can always write something that will convert negative numbers to None and non-negative to Some(n) if it bothers you:

implicit class OptionOutNegatives(val underlying: Int) extends AnyVal {
  def asIndex = if (underlying < 0) None else Some(underlying)
}
like image 146
Rex Kerr Avatar answered Oct 26 '22 23:10

Rex Kerr