Liam Haworth Liam Haworth - 3 months ago 7
Scala Question

Val defined in package object unaccessable in other classes

I have the following package object with a

val
declared in it

package au.com.someproject.protocol

package object helpers {
val etcdRoot = "someproject.com.au"
}


This package object is declared as part of an API, when I import the API into another project and I try to access the variable I meet with the following error

[error] /home/user/git/company/project/project-agent/src/main/scala/au/com/someproject/project_agent/cluster/StatusMonitor.scala:52: not found: value etcdRoot
[error] etcdClient.setKey(s"$etcdRoot/kumo/peers/${systemCluster.selfAddress.host.get}", systemCluster.selfAddress.port.get.toString, new Some(40.seconds))


I'm importing the variable like so, how I would except it should be done

import au.com.someproject.protocol.helpers._


But yet I get the error, is there something I am doing wrong with the declaration or importing?

Answer

There's usually a catch with package objects, they have to be manually placed inside the package folder, meaning I would expect your directory structure to look like this before the import would work.

src/main/scala/au/com/someproject/protocol/helpers/helpers.scala

And inside the helpers/, you define your package object. Sometimes you are tempted to have it like the below:

src/main/scala/au/com/someproject/protocol/helpers.scala

The above doesn't actually define the package object on the helpers package, you need to follow the specific directory structure and manually define the package before you define the package object inside it.