Scala in Depth演示了Loaner模式:
def readFile[T](f: File)(handler: FileInputStream => T): T = {
val resource = new java.io.FileInputStream(f)
try {
handler(resource)
} finally {
resource.close()
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
readFile(new java.io.File("test.txt")) { input =>
println(input.readByte)
}
Run Code Online (Sandbox Code Playgroud)
此代码看似简单明了.什么是Scala中Loaner模式的"反模式",以便我知道如何避免它?
我很困惑为什么我需要将清理代码放在一个finally块中关闭流.
我已经读过finally块中的代码无论如何都会运行(是否存在异常); 并且在finally块运行之后,该方法的其余部分继续.
我的问题是:如果方法的其余部分必须继续,那么为什么我不在函数中的try/catch块之后放入清理代码?
这是一个我有疑问的例子(来自另一个SO问题):
public static void writeToFile (final String filename)
{
PrintWriter out = null;
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(filename);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(fos, "UTF-8")));
for (final String line : log)
{
out.println(line);
}
out.flush();
out.close();
}
catch (final Exception e)
{
System.err.println("Unable to write log to file.");
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (final IOException e)
{
System.err.println("Unable to write log to file.");
}
}
} …Run Code Online (Sandbox Code Playgroud)