Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

when operator in scala

View whenInScala.scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/**
* A syntactic sugar corresponding to the Lisp's when. Execute the body
* when the pred evaluates to true.
* @param condition A predicate or value that evaluate to a Boolean
* @param block A valid block of scala code
*/
def when (condition : => Boolean)( block : => Unit)
{
if (condition){ block }
}
 
//A left associative version from the redditor elbowich
implicit def `when for function0`[A](f: => A) = new {
def when(cond: Boolean) = if(cond) Some(f) else None
}

This is great for side effect driven code, but this may also be useful to you for code that you care about the return value ( which should be most of the time :) ):

def when[A] ( condition : => Boolean ) ( block : => A ) : Option[A] = {
  if ( condition ) {
     Some( block )
  } else {
    None
  }
} 

I'm not quite sure whether this is useful to you, but it may be an interesting thing if you're new to Scala and couldn't quite figure out how you would return a value from when without returning a blasphemous 'null' value. ;)

Happy Scala-ing!

Owner

Yep! Thanks for the suggestion!
Bye!
Alfredo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.