Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (Option.nonEmpty) vs Option.foreach

Tags:

scala

I want to perform some logic if the value of an option is set.

Coming from a java background, I used:

if (opt.nonEmpty) {
   //something
}

Going a little further into scala, I can write that as:

opt.foreach(o => {
  //something 
})

Which one is better? The "foreach" one sounds more "idiomatic" and less Java, but it is less readable - "foreach" applied to a single value sounds weird.

like image 918
Bozho Avatar asked Aug 10 '13 16:08

Bozho


1 Answers

Your example is not complete and you don't use minimal syntax. Just compare these two versions:

if (opt.nonEmpty) {
  val o = opt.get
  // ...
}

// vs

opt foreach {
  o => // ...
}

and

if (opt.nonEmpty)
  doSomething(opt.get)

// vs

opt foreach doSomething

In both versions there is more syntactic overhead in the if solution, but I agree that foreach on an Option can be confusing if you think of it only as an optional value.

Instead foreach describes that you want to do some sort of side effects, which makes a lot of sense if you think of Option being a monad and foreach just a method to transform it. Using foreach has furthermore the great advantage that it makes refactorings easier - you can just change its type to a List or any other monad and you will not get any compiler errors (because of Scalas great collections library you are not constrained to use only operations that work on monads, there are a lot of methods defined on a lot of types).

like image 129
kiritsuku Avatar answered Oct 12 '22 15:10

kiritsuku