Skip to content

Instantly share code, notes, and snippets.

@fsarradin
Created September 9, 2022 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fsarradin/0af54d689c4538ce27bb57e3db5cb683 to your computer and use it in GitHub Desktop.
Save fsarradin/0af54d689c4538ce27bb57e3db5cb683 to your computer and use it in GitHub Desktop.
Non-strict evaluation in Scala
/**
* Try to solve this puzzle only by modifying the function [[doubleMessage]].
* All checks should succeed.
*
* This exercise must be run in a worksheet.
* - One is available on the Web with Scastie (https://scastie.scala-lang.org)
* - One is available in IntelliJ IDEA
* (https://www.jetbrains.com/help/idea/work-with-scala-worksheet-and-ammonite.html)
*
* Click on "> Run". See the results in the console. And try to solve this
* puzzle by using call-by-value and lazy declaration.
*/
def doubleMessage(displayIt: Boolean, message: => String): String =
if (displayIt)
s"$message $message"
else
"(nope)"
// vvvv DON'T TOUCH THIS vvvv
object MessageCheck:
def check(description: String, condition: Boolean): Unit =
if (condition)
println(s"$description: ${Console.GREEN}Success${Console.RESET}")
else
println(s"$description: ${Console.RED}Failure${Console.RESET}")
private var x = 0
def message = {
x += 1
"hello"
}
def run: Unit =
check("should answer (nope) when no display", doubleMessage(displayIt = false, message) == "(nope)")
check("x should not have increased", x == 0)
check("should answer message twice when display", doubleMessage(displayIt = true, message) == "hello hello")
check("x should have increased only once", x == 1)
MessageCheck.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment