0

I was told by someone to make the companion object function private and import the companion object to the class and then access the function in the class.

The following code does not work in the repl.

Example:

object Foo {
  private def bar(i: Int): Boolean = i == 5
}

class Foo{
  import Foo._

  bar(0) 
}

object Foo {
  private def bar(i: Int): Boolean = i == 5
}

class Foo{
  import Foo._

  Foo.bar(0) 
}
scala> object Foo {
     |   private def bar(i: Int): Boolean = i == 5
     | }
defined object Foo

scala> 

scala> class Foo{
     |   import Foo._
     | 
     |   bar(0) 
     | }
<console>:15: error: not found: value bar
         bar(0)
         ^

scala> 

scala> object Foo {
     |   private def bar(i: Int): Boolean = i == 5
     | }
defined object Foo

scala> 

scala> class Foo{
     |   import Foo._
     | 
     |   Foo.bar(0) 
     | }
<console>:15: error: method bar in object Foo cannot be accessed in object Foo
         Foo.bar(0)
             ^
depappas
  • 53
  • 4
  • 1
    Use :paste as Mario mentioned below. To eval the paste you need to use cntl-d. Note that :paste mode is required because there are blank lines. If there are no blank lines then :paste mode does not seem to be required. – depappas Jan 26 '20 at 00:45
  • 1
    REPL will even warn you that they are not actually companions because they're defined separately. You probably don't get the warning because you get a compile error instead. – Jasper-M Jan 26 '20 at 10:13

1 Answers1

3

According to docs

A companion object and its class can access each other’s private members

The problem might be that in REPL it is not recognising it as companion. Try with :paste mode enabled.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98