Scala value not found

2019-01-28 12:04发布

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> 

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

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?

I'm running Scala 2.10.3 installed via homebrew in Mac Os X 10.9

Thanks a lot

(I'm having, of course, the same problem using SBT)

标签: class scala sbt
2条回答
ゆ 、 Hurt°
2楼-- · 2019-01-28 12:46

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()

(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).

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()
查看更多
Explosion°爆炸
3楼-- · 2019-01-28 13:05
scala> val f = new Foo()
f: Foo = Foo@525c6957
查看更多
登录 后发表回答