This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Access companion object's private values in companion class

1 reply
Karsten Breit
Joined: 2009-03-11,
User offline. Last seen 42 years 45 weeks ago.
Hi guys,

reading the language spec

The private modifier can be used with any definition or declaration in a tem-
plate. Such members can be accessed only from within the directly enclosing
template and its companion module or companion class (§Example 5.4.1).
They are not inherited by subclasses and they may not override definitions in
parent classes.

I'd assume that the following piece of code would work

class C {
def test(){
println(C.x)
}
}
object C {
private val x = "xvalue"
def apply() = new C
}

val c = C()
c.test

but the interpreter comes around with

(fragment of access.scala):13: error: value x cannot be accessed in object C
println(C.x)

Obviously my assumption was wrong, but where's my failure?

Thanks a lot
Karsten
Jorge Ortiz
Joined: 2008-12-16,
User offline. Last seen 29 weeks 3 days ago.
Re: Access companion object's private values in companion clas
It's not your failure, it's the interpreter's. Because it reads in things one at a time, it has trouble associating things like a class and its companion object. Try wrapping them in another object so the interpreter compiles them together:

object Foo {
  class C {
    def test(){
      println(C.x)
    }
  }
  object C {
    private val x = "xvalue"
    def apply() = new C
  }
}

val c = new Foo.C
c.test

--j

On Wed, Mar 11, 2009 at 3:29 AM, Karsten Breit <kab [at] spreadshirt [dot] net> wrote:
Hi guys,

reading the language spec

The private modifier can be used with any definition or declaration in a tem-
plate. Such members can be accessed only from within the directly enclosing
template and its companion module or companion class (§Example 5.4.1).
They are not inherited by subclasses and they may not override definitions in
parent classes.

I'd assume that the following piece of code would work

class C {
def test(){
println(C.x)
}
}
object C {
private val x = "xvalue"
def apply() = new C
}

val c = C()
c.test

but the interpreter comes around with

(fragment of access.scala):13: error: value x cannot be accessed in object C
println(C.x)

Obviously my assumption was wrong, but where's my failure?

Thanks a lot
Karsten

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland