Well I just started this little jaunt into Scala. The book I got through Amazon (Kindle App) is “Beginning Scala” by David Pollak. I spoke with David when discussing whether Lift was a good fit for a project I have. Now I am reading his book.
The book was written for an earlier version of Scala. Namely; Scala 2.7.8. I am using it under 2.8.0. There are some differences in how some of the methods are applied, and what they return. Most notably was the input.getLines method in the ‘sum.scala’ example.
The error when executing sum.scala
# scala sum.scala
/home/scala/sum.scala:20: error: missing arguments for method collect in trait Iterator;
follow this method with `_’ if you want to treat it as a partially applied function
val lines = input.getLines.collect
^
one error found
What you need to do is add a .toSeq at the end for
val lines = input.getLines.toSeq
Whole file
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”)
val input = Source.fromInputStream(System.in)
val lines = input.getLines.toSeq
println(“Sum “+sum(lines))
Run it on your box, and it should ask you for some numbers and sum them up for ya. As David puts it ” [this program] makes use of many of Scala’s features including function passing, immutable data structures, and type inference.”
I think I am going to have fun learning Scala.