Skip to content

Instantly share code, notes, and snippets.

@nenono
Last active August 29, 2015 14:17
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 nenono/1f8f2ba009e4e4e26c81 to your computer and use it in GitHub Desktop.
Save nenono/1f8f2ba009e4e4e26c81 to your computer and use it in GitHub Desktop.
Scalaの名前呼び出しとlazyについて
// 評価戦略など
object Evaluations {
def isEven(x: Int) = x % 2 == 0
// 偶数の時だけmessageをprintします。messageは名前呼び出しな引数
def printWhenEven(x: Int, message: => String) = {
if(isEven(x)) println(message)
else println("...")
}
// 名前呼び出しの確認
def testCallByName = {
// makeMessage関数が実行されたらprintされます(確認用)
def makeMessage (str:String) = {
println(s"called with:${str}")
str
}
printWhenEven(1, makeMessage("I love you."))// makeMessageは実行されず、printもされません
printWhenEven(2, makeMessage("The moon is beautiful."))// makeMessageが実行されて、printもされます
}
def testLazy = {
def makeLazy = {
println("evaluated!")
42
}
lazy val x = makeLazy
println ("testLazy1")// この時点ではxは計算されません
val y = x + 1 // xが使われるので、ここでevaluated!がprintされます
println (s"testLazy2 y:${y}")
}
def main(args: Array[String]) {
testCallByName
testLazy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment