I’m reading Programming Scala (O’reilly) It’s a really good book, and is easy to follow.
The problem is that there’s an example about Enumerations that is bugged and as a started really don’t know why is it.
So, here’s the code:
// code-examples/Rounding/enumeration-script.scala
object Breed extends Enumeration {
val doberman = Value("Doberman Pinscher")
val yorkie = Value("Yorkshire Terrier")
val scottie = Value("Scottish Terrier")
val dane = Value("Great Dane")
val portie = Value("Portuguese Water Dog")
}
// print a list of breeds and their IDs
println("ID\tBreed")
for (breed <- Breed) println(breed.id + "\t" + breed)
// print a list of Terrier breeds
println("\nJust Terriers:")
Breed.filter(_.toString.endsWith("Terrier")).foreach(println)
When i try to execute it in eclipse (inside of a main method) it doesn’t even compile. When i want to execute the script with the scala command it works, but says that there are deprecation warnings. So i execute it again with -deprecation flag and it shows the warnings:
>> scala -deprecation enumeration-script.scala
/home/{me}/code/enumeration-script.scala:13: warning: method foreach in class Enumeration is deprecated: use values.foreach instead
for (breed <- Breed) println(breed.id + "\t" + breed)
^
/home/{me}/code/enumeration-script.scala:17: warning: method filter in class Enumeration is deprecated: use values.filter instead
Breed.filter(_.toString.endsWith("Terrier")).foreach(println)
^
two warnings found
ID Breed
0 Doberman Pinscher
1 Yorkshire Terrier
2 Scottish Terrier
3 Great Dane
4 Portuguese Water Dog
Just Terriers:
Yorkshire Terrier
Scottish Terrier
So, i read this and change the code, and it now works fine, the changes are:
// code-examples/Rounding/enumeration-script.scala
object Breed extends Enumeration {
val doberman = Value("Doberman Pinscher")
val yorkie = Value("Yorkshire Terrier")
val scottie = Value("Scottish Terrier")
val dane = Value("Great Dane")
val portie = Value("Portuguese Water Dog")
def main(args: Array[String]) {
// print a list of breeds and their IDs
println("ID\tBreed")
for (breed <- Breed.values) println(breed.id + "\t" + breed)
// print a list of Terrier breeds
println("\nJust Terriers:")
Breed.values.filter(_.toString.endsWith("Terrier")).foreach(println)
}
}
Please note that i put the execution code inside a main method.
Now, why is that? Is for the version of Scala? Should i be worried for the other examples? Update my Scala version? Why it doesn’t run on eclipse?
My version of Scala is 2.8.1.final
I guess you used the Eclipse plugin for version 2.9/2.10 instead of the one for version 2.8, that’s why it worked in your old Scala distribution, but not with Eclipse which ships with its own version.
The method in question was deprecated and removed subsequently.
Suggestion: Update to the latest version (2.9.1 currently).