Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Friday, May 25, 2012

How to workaround Class and Companion object in REPL

As you can see below the companion object can't access the private variable from the Class Person. This is due to a different scope. To fix it you will need to define a container (can be called something else by the way).
scala> class Person {
     | private var firstname = "Robby"
     | private var lastname = "Pelssers"
     | }
defined class Person

scala> object Person {
     | def getFirstName(p: Person) = p.firstname
     | }
:9: error: variable firstname in class Person cannot be accessed in Person
       def getFirstName(p: Person) = p.firstname

scala> object container {
     |   class Person {
     |      private var firstname = "Robby"
     |      private var lastname = "Pelssers"
     |   }
     |
     |   object Person {
     |       def getFirstName(p: Person) = p.firstname
     |   }
     | }
defined module container

scala> import container.Person
import container.Person

scala> val person = new Person()
person: container.Person = container$Person@1a71d29a

scala> Person.getFirstName(person)
res0: java.lang.String = Robby

Important side note!! As of Scala 2.9.x you can use the :paste command and everything will work normally.
scala> :paste
// Entering paste mode (ctrl-D to finish)

class Person {
  private var firstname = "Robby"
  private var lastname = "Pelssers"
}

object Person {
  def getFirstName(p: Person) = p.firstname
}

// Exiting paste mode, now interpreting.

defined class Person
defined module Person

scala> Person.getFirstName(new Person())
res0: java.lang.String = Robby

No comments:

Post a Comment