Skip to content

Instantly share code, notes, and snippets.

@gustavoamigo
Last active May 23, 2018 10:30
Show Gist options
  • Save gustavoamigo/a0996e4c6bf0cf139f4b to your computer and use it in GitHub Desktop.
Save gustavoamigo/a0996e4c6bf0cf139f4b to your computer and use it in GitHub Desktop.
Ruby like postfix conditionals with Scala
implicit class RicherConditional[T](ifTrue: => T ) {
def unless(condition: Boolean) = new WhenOrOtherwise(!condition, ifTrue)
def when(condition: Boolean) = new WhenOrOtherwise(condition, ifTrue)
}
class WhenOrOtherwise[T] (condition: Boolean, ifTrue: => T) {
def otherwise(ifOtherwise: => T) = if(condition) ifTrue else ifOtherwise
def otherwiseNone = if(condition) Some(ifTrue) else None
}
println ("1" unless 1==2 otherwise "3")
println ("1" unless 1==1 otherwise "3")
println ("1" when 1==1 otherwiseNone)
println ("1" when 1==2 otherwiseNone)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment