Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala value not found

Tags:

class

scala

sbt

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)

like image 849
besil Avatar asked Dec 09 '22 08:12

besil


1 Answers

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()
like image 176
Jesper Avatar answered Dec 28 '22 03:12

Jesper