Created
March 17, 2015 06:36
-
-
Save nenono/d122e530b4c044bef2a0 to your computer and use it in GitHub Desktop.
Scalaでクロージャーを作ってみる
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 Closures { | |
// lambda式はclosureを作ります | |
def makeCounter = { | |
var x = 0 // varは再代入可能な変数の定義 | |
val f = () => { // valは束縛、() => {}の部分はラムダ式 | |
x += 1 | |
x // コードブロック中で最後の式が評価結果になります | |
} | |
f | |
// fは ()=>Int 型 | |
// ここに関しては実際のところ一時変数fを使う必要はないです。 | |
} | |
def counterTest = { | |
val counter = makeCounter | |
println(counter()) | |
println(counter()) | |
println(counter()) | |
println(counter()) | |
// 1, 2, 3, 4 | |
} | |
def main(args: Array[String]) { | |
counterTest | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment