我正在阅读 Programming Scala (O'reilly)这是一本非常好的书,而且很容易理解。
问题是有一个关于枚举的例子被窃听了,作为一个初学者真的不知道为什么会这样。
所以,这是代码:
// 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)
当我尝试在 eclipse 中执行它时(在 main 方法内部),它甚至无法编译。当我想用 scala
命令执行脚本时,它可以工作,但说有弃用警告。所以我用 -deprecation
标志再次执行它并显示警告:
>> 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
所以,我读了这篇文章并更改了代码,现在它工作正常,更改是:
// 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)
}
}
请注意,我将执行代码放在 main
方法中。
现在,这是为什么呢?是针对Scala的版本?我应该担心其他例子吗?更新我的 Scala 版本?为什么它不在 eclipse 上运行?
我的 Scala 版本是 2.8.1.final
最佳答案
所以,我在书的勘误表中找到了它:
Under version 2.8.0.Beta1-prerelease, there are deprecation warnings with the source code.
作者回复:
Yes, apparently this is an API change in 2.8. If you run the script with "scala -deprecation ...", you'll see the warnings in more detail (I wish this flag was on by default). You have to use "for (breed <- Breed.values)" instead of "for (breed <- Breed)" and similarly, "Breed.values.filter" instead of "Breed.filter" to eliminate the warnings. However, the values method isn't available in 2.7.X.
关于Scala 示例代码和弃用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7423448/