Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

class - Scala value not found

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...