Tuesday, 19 February 2008

Translating Java to Scala

Java code to translate


public byte[] getBytes(String path) throws IOException,
ClassNotFoundException {
System.out.println("reading: " + path);
File f = new File(classpath + (classpath.length()==0?"":File.separator)
+ path.replace('.', File.separatorChar) + ".class");
int length = (int) (f.length());
if (length == 0) {
System.out.println("File length is zero");
throw new IOException("File length is zero: " + path);
} else {
byte[] bytecodes;
FileInputStream fin = null;
DataInputStream in = null;
try {
fin = new FileInputStream(f);
in = new DataInputStream(fin);

bytecodes = new byte[length];
in.readFully(bytecodes);
} finally {
try {
in.close();
} catch (IOException e) {
// We tried - keep going - the bytecodes may still be ok
}
try {
fin.close();
} catch (IOException e) {
// We tried - keep going - the bytecodes may still be ok
}
}
return bytecodes;
}
}

First attempt


def getBytes(path: String) : Array[Byte] = {
println("reading: " + path);
val f = new File(classpath + (if (classpath.length()==0) "" else File.separator) + path.replace('.', File.separatorChar) + ".class");
val length:Int = f.length().asInstanceOf[Int];
if (length == 0) {
println("File length is zero");
throw new IOException("File length is zero: " + path);
} else {
var fin: FileInputStream = null
var in: DataInputStream = null
var bytecodes:Array[Byte] = null
try {
fin = new FileInputStream(f);
in = new DataInputStream(fin);
bytecodes = new Array[Byte](length);
in.readFully(bytecodes);
} finally {
try { in.close(); } catch { case _ => }
try { fin.close(); } catch { case _ => }
}

return bytecodes;
}
}

Much nicer using resource management


def getBytes(path: String) : Array[Byte] = {
println("reading: " + path);
val f = new File(classpath + (if (classpath.length()==0) "" else File.separator) + path.replace('.', File.separatorChar) + ".class");
val length:Int = f.length().asInstanceOf[Int];
if (length == 0) {
println("File length is zero");
throw new IOException("File length is zero: " + path);
} else {
val bytecodes = new Array[Byte](length);
withDataInputStream(f) { dis =>
dis.readFully(bytecodes);
}
return bytecodes;
}
}

def withDataInputStream(f: File)(operation: DataInputStream => Unit) {
val fin = new FileInputStream(f)
val in = new DataInputStream(fin);
try {
operation(in)
} finally {
try { in.close(); } catch { case _ => }
try { fin.close(); } catch { case _ => }
}
}
Post a Comment