Search code examples
scalacompanion-object

Cannot access companion object but can instantiate class


I have the following source code:

abstract class Foo{
}
object Foo{
    def foo(f : String) = println(f)
}
object Tester extends App{
    class Bar extends Foo
    val b = new Bar()
    Bar.foo("bar")
}

When I try to run this with sbt I get the error:


Foo.scala:9:5: not found: value Bar
[error]     Bar.foo("bar") // this line won't compile...
[error]     ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 0 s, completed Mar 12, 2020 10:29:49 AM

Why can't I refer to Bar even though I have declared it as a class in the app.


Solution

  • Why can't I refer to Bar even though I have declared it as a class in the app.

    You are not referring to it as a class. You are referring to an object named Bar. There is no such object in scope.