Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return early without return statement?

How to write an early-return piece of code in scala with no returns/breaks?

For example

for i in 0..10000000
  if expensive_operation(i)
     return i
return -1
like image 718
Michele Piccolini Avatar asked Sep 27 '19 11:09

Michele Piccolini


2 Answers

How about

 input.find(expensiveOperation).getOrElse(-1)
like image 115
Thilo Avatar answered Nov 11 '22 07:11

Thilo


You can use dropWhile

Here an example:

Seq(2,6,8,3,5).dropWhile(_ % 2 == 0).headOption.getOrElse(default = -1) // -> 8

And here you find more scala-takewhile-example

With your example

(0 to 10000000).dropWhile(!expensive_operation(_)).headOption.getOrElse(default = -1)`
like image 37
pme Avatar answered Nov 11 '22 07:11

pme