ps0604 ps0604 - 20 days ago 5
Scala Question

Make class elements accessible in companion object

I need to access the list object in

someFunction
below, however I get a compilation error
not found: value list
. How to access the list from the companion object?

class HelloScala {
val list = List (1,2,3)
}

object HelloScala {

def someFunction = {
println(list)
}

}

Answer

In order to access members of a class, you have to instantiate that class:

object HellowScala {
  def someFunction = {
    println(new HelloScala().list)
  }
}

More likely, what you want to do is move the list member to the companion object:

class HelloScala {
   // you can access the companion members here
   val x = HelloScala.list
}

object HelloScala {

  val list = List (1,2,3)

  def someFunction  = {
    println(list)
  }
}