Last active
August 29, 2015 13:58
-
-
Save ElectricCoffee/10023572 to your computer and use it in GitHub Desktop.
the idea is to have a while-loop with an else statement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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