scala - if (Option.nonEmpty) vs Option.foreach -


i want perform logic if value of option set.

coming java background, used:

if (opt.nonempty) {    //something } 

going little further scala, can write as:

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

which 1 better? "foreach" 1 sounds more "idiomatic" , less java, less readable - "foreach" applied single value sounds weird.

your example not complete , don't use minimal syntax. compare these 2 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 more syntactic overhead in if solution, agree foreach on option can confusing if think of optional value.

instead foreach describes want sort of side effects, makes lot of sense if think of option being monad , foreach method transform it. using foreach has furthermore great advantage makes refactorings easier - can change type list or other monad , not compiler errors (because of scalas great collections library not constrained use operations work on monads, there lot of methods defined on lot of types).


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -