Skip to content

Instantly share code, notes, and snippets.

@Krasnyanskiy
Last active April 17, 2016 13:42
Show Gist options
  • Save Krasnyanskiy/cf6b537d60aa369ed4cd5e2e8c80e669 to your computer and use it in GitHub Desktop.
Save Krasnyanskiy/cf6b537d60aa369ed4cd5e2e8c80e669 to your computer and use it in GitHub Desktop.
-scala: while -> recursive
def `while`(condition: => Boolean)(command: => Unit): Unit = if (condition) {
command
`while`(condition)(command)
}
var i = 10
`while`{ i = i - 1; i > 0 } { println(i) }
@Krasnyanskiy
Copy link
Author

Make your own while loop via recursion.

@Krasnyanskiy
Copy link
Author

Please note that you need to call expression in the second parentheses by name, otherwise you evaluate it only once.

Not a lazy expression
command: Unit

@Krasnyanskiy
Copy link
Author

Since (command: => Unit) we could do not pass an expression into the while

`while` { i = i - 1; i > 0 } {}

Compiler will add a Unit literal () implicitly to { () }. And it is just fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment