A friend of mine is learning Scala and wrote this simple code to keep track of the longest line in a file:
val longest = (filename:String) => {
val is = new FileInputStream(filename)
val buf = new Array[Byte](1024)
var longest=0 //keep track of the longest line
var lastPos=0
var read=0
try {
read = is.read(buf)
while (read > 0) {
for (i<-0 until read) {
if (buf(i) == '\n') {
val size=i-lastPos-1
lastPos=i
if (size>longest) {
longest=size
}
}
}
lastPos-=buf.length
read=is.read(buf)
}
} finally {
is.close()
}
longest
}
I'm new to Scala too, but I'm pretty sure there's a lot of room for flatMaps and other functions in this code.
Could someone post a functional version of this?