Skip to content

Instantly share code, notes, and snippets.

@nenono
Created March 17, 2015 06:36
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/d122e530b4c044bef2a0 to your computer and use it in GitHub Desktop.
Save nenono/d122e530b4c044bef2a0 to your computer and use it in GitHub Desktop.
Scalaでクロージャーを作ってみる
// クロージャー
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