Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Last active August 29, 2015 13:58
Show Gist options
  • Save ElectricCoffee/10023572 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/10023572 to your computer and use it in GitHub Desktop.
the idea is to have a while-loop with an else statement
// what it tries to solve:
var cond = true
if(cond) {
while(cond) {
// do something
}
}
else {
// do something else
}
// implementation:
object While {
def apply(condition: => Boolean)(f: => Unit) = new While(condition)(f)
}
class While private(cond: => Boolean)(f1: => Unit) {
private val init = cond
while(cond) f1
def Else(f2: => Unit): Unit = if(!init) f2
}
// usage:
var c = true
While(c) {
println("while is true")
c = false
} Else {
println("while is false")
}
// will print "while is true" if true, and "while is false" only when while is false initially
// some cons about this: brackets are mandatory,
// and Else MUST come after the closing bracket, it cannot be on its own line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment