Last active
August 29, 2015 14:17
-
-
Save nenono/1f8f2ba009e4e4e26c81 to your computer and use it in GitHub Desktop.
Scalaの名前呼び出しとlazyについて
This file contains 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
// 評価戦略など | |
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