Suppose I have a function f(n:Int):Option[String]. I would like to find such 1 <= k <= 10 that f(k) is not None. I can code it as follows:
(1 to 10).find(k => f(k).isDefined)
Now I would like to know both k and f(k).
val k = (1 to 10).find(f(_).isDefined) val s = f(k)
Unfortunately, this code invokes f(k) twice. How would you find k and f(k) at once ?
My first try would be:
The use of
viewavoids creating intermediatemap. Or even better with pattern matching and partial function:This returns
Option[(Int, java.lang.String)](Noneif no element satisfyingfis found).You might also experiment with
.zipWithIndex.