I’ve tried to run this code under scala 2.7.3 and 2.7.7 and everytime i get this error. What is wrong?
import scala.io._
def toInt(in: String): Option[Int] =
try {
Some(Integer.parseInt(in.trim))
} catch {
case e: NumberFormatException => None
}
def sum(in: Seq[String]) = {
val ints = in.flatMap(s => toInt(s))
ints.foldLeft(0)((a, b) => a + b)
}
println("Enter some numbers and press ctrl-D (Unix/Mac) ctrl-C (Windows)")
val input = Source.fromInputStream(System.in)
val lines = input.getLines.collect
println("Sum "+sum(lines))
I’ve tried to isolate the problem and it seems that it has to do with the way you input your values.
For example, the following code snippet works as expected, printing 6.
Therefore, the problem must lie somewhere in the lines to follow. I think the main culprit is what Ctrl-C actually does on Windows combined with how the Scala interpreter runs your scripts. The last line of the screenshot you have attached to the question was the starting point. It suggests that somewhere, a batch job is running and the Ctrl-C has sent a signal to kill that batch job. This is actually none other than the scala interpreter itself (
scala.bat). Therefore, when you press Ctrl-C, instead of just killing the input stream, you send a signal to kill the whole batch job running your program!So the error has something to do with this action. I’ve looked at how
scalaruns your script. It seems that a folder namedscalascriptXXXXXXXXXXXXXXXXXXX(where XX… represent 19 pseudorandom digits) is created in%TEMP%where all the compiled stuff needed is placed. There, a file calledMain$$anon$1$$anonfun$1.classis created — this represents the anonymous function that is passed to theflatMapfunction. It seems that this file is created in parallel with the running of the program. Therefore, if you kill your process before it has a chance to do this compilation, you will get theClassNotFoundException.Now, it’s quite strange that you get this error all the time you run your script. I have managed to get it occasionally. Always though, as soon as I press Ctrl-C I get the
Terminate batch job (Y/N)?prompt. Sometimes it is accompanied with an exception. Sometimes not. I think it again has to do with the creation of theMain$$anon$1$$anonfun$1.class. If I wait a while, I get no exception. If I press Ctrl-C straight away after start, I get the exception.After quite a lot of runs I managed to get a complete stack trace(I think… as the Ctrl-C stops the stack trace from being dumped as well), pointing to the main culprit — a
FileNotFoundException.I would therefore recommend using a better method to input your values. Maybe try
Console.in.readLine? and stop when you get a non-numeric line.Or, if you really want to indicate the end of a stream, try using Ctrl-Z (Ctrl-C is the kill process signal).
— Flaviu Cipcigan