未找到 Scala 值 [英] Scala value not found
问题描述
我的 scala 解释器/编译器有一个非常奇怪的行为.
I'm having a very strange behaviour from my scala interpreter/compiler.
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class Foo {
| def bar = {
| println("Foo is bar!")
| }
| }
defined class Foo
scala> var f = Foo()
<console>:7: error: not found: value Foo
var f = Foo()
^
scala>
我也尝试将它放在单个文件 main.scala 中
I also tried putting it in a single file main.scala
class Foo {
def bar = {
println("foo is bar!")
}
}
object Main {
def main(args: Array[String]): Unit = {
println("ciao")
Foo()
}
}
$ scalac main.scala
main.scala:10: error: not found: value Foo
Foo()
^
one error found
来自Java/Python,我真的不明白为什么找不到简单的类Foo,尤其是在解释器中.我错过了什么?
Coming from Java/Python, I really don't understand why the simple class Foo is not found, especially in the interpreter. What am I missing?
我正在运行通过 Mac Os X 10.9 中的自制软件安装的 Scala 2.10.3
I'm running Scala 2.10.3 installed via homebrew in Mac Os X 10.9
非常感谢
(当然,我在使用 SBT 时遇到了同样的问题)
(I'm having, of course, the same problem using SBT)
推荐答案
您需要使用 new
关键字来创建一个新对象,或者为您的类添加一个伴随对象 Foo
使用 apply()
方法来创建一个新的 Foo
对象.
You need to either use the new
keyword to create a new object, or add a companion object for your class Foo
with an apply()
method to create a new Foo
object.
object Foo {
def apply() = new Foo()
}
// This is short syntax for Foo.apply()
val f = Foo()
(注意:如果您在 REPL 中执行此操作,则需要使用 :paste
同时粘贴类和对象).
(Note: If you do this in the REPL, you'll need to use :paste
to paste both the class and the object at the same time).
你也可以把Foo
做成一个case类;当您这样做时,将自动创建一个带有 apply
方法的伴随对象.
You can also make Foo
a case class; when you do that, a companion object with apply
method will be automatically created.
case class Foo
val f = Foo()
这篇关于未找到 Scala 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!