Skip to content

Instantly share code, notes, and snippets.

@nenono nenono/Evaluations.scala
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.