Last active
December 17, 2015 19:28
-
-
Save gkojax/5660121 to your computer and use it in GitHub Desktop.
社内勉強会でusingについて説明
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
// 単純なopen、close | |
val fileName = "text.txt" | |
val resource = new BufferedReader(new FileReader(new File(fileName))) | |
resource.readLine | |
resource.close |
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
// try、catchをちゃんとやる | |
val resource = new BufferedReader(new FileReader(new File(fileName))) | |
try { | |
resource.readLine | |
} finally { | |
resource.close | |
} |
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
// 似たようなファイルの読み書き処理が増えると野暮ったくなる | |
val resource = new BufferedReader(new FileReader(new File(fileName))) | |
try { | |
val l = resource.readLine | |
l.head | |
} finally { | |
resource.close | |
} | |
val resource = new BufferedReader(new FileReader(new File(fileName))) | |
try { | |
val l = resource.readLine | |
l.tail | |
} finally { | |
resource.close | |
} |
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
// ファイル処理にかかわるはusingの中に書いて、機能を分離する。 | |
def using[A, R <: {def close()}](resource: R)(func: R => A): A = { | |
try { | |
func(resource) | |
} finally { | |
resource.close | |
} | |
} | |
val in = new BufferedReader(new FileReader(new File(fileName))) | |
using(in) { resource => | |
val l = resource.readLine | |
l.head | |
} | |
val in = new BufferedReader(new FileReader(new File(fileName))) | |
using(in) { resource => | |
val l = resource.readLine | |
l.tail | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment