Why does Scala indexOf (in a list, etc.) return an Int instead of the [Int] option?

I want to write really nice idiomatic code for Scala list indexOf foo getOrElse Int.MaxValue , but now I have to settle for idiotic code looking in Java val result = list indexOf foo; if (result < 0) Int.MaxValue else result 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]

+5
source share
3 answers

That should not be so.

 scala> "abcde" index 'c' res0: psp.std.Index = 2 scala> "abcde" index 'z' res1: psp.std.Index = -1 scala> "abcde" index 'z' match { case Index(n) => n ; case _ => MaxInt } res2: Int = 2147483647 // Emphasizing that at the bytecode level we still return an Int - no boxing. scala> :javap psp.std.SeqLikeExtensionOps [...] public abstract int index(A); descriptor: (Ljava/lang/Object;)I 

Which of psp-std you can run "sbt console", and then above.

+3
source

This is for compatibility with Java and for speed. You will need to double the answer (first in java.lang.Integer , then Option ) instead of just returning a negative number. This may take about ten times.

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

 implicit class OptionOutNegatives(val underlying: Int) extends AnyVal { def asIndex = if (underlying < 0) None else Some(underlying) } 
+10
source

To solve the secondary question, squeezed between the primary and tertiary, there are other methods for performing operations such as processing indexes and finding or collecting elements that satisfy the predicate.

 scala> ('a' to 'z').zipWithIndex find (_._1 == 'k') map (_._2) res6: Option[Int] = Some(10) 

Usually you do something interesting with the element that you find.

+1
source

Source: https://habr.com/ru/post/1200953/


All Articles