Faheem Sohail
Faheem Sohail

Reputation: 846

Accessing Companion Class variable from another class

I am really new to scala. I am trying to access a companion class variable from outside the class. How do I do this if at all possible without creating an instance of the class.

In the following example, I can access INTERNAL_COST_REQUESTS from within the YotascaleCostProcessing class

package com.yotascale
class YotascaleCostProcessing extends YotascaleActorSystem{

 //companion object
 object YotascaleCostProcessing{
 val INTERNAL_COST_REQUESTS = "internal-cost-requests"
 val INTERNAL_COST_UPDATES = "internal-cost-updates"
}

def setupInfrastructure() = {
    QueueService.createQueue(YotascaleCostProcessing.INTERNAL_COST_REQUESTS)
    QueueService.createQueue(YotascaleCostProcessing.INTERNAL_COST_UPDATES)
  }
}

When I do YotascaleCostProcessing.INTERNAL_COST_UPDATES from another class in another package, I get an error "not found: value YotascaleCostProcessing" even though the import for YotascaleCostProcessing is there. The only way this works is when I do this: new YotascaleCostProcessing().YotascaleCostProcessing.INTERNAL_COST_UPDATES

package com.yotascale.service.cost.setup;
import com.yotascale.YotascaleCostProcessing
class MetadataNotificationConfiguringActor(message:Message) extends UntypedActor {

def configureBucket() = {
 val realtimeupdates = QueueService.getQueueURL(YotascaleCostProcessing.INTERNAL_COST_REQUESTS)   
}
}

Upvotes: 2

Views: 3176

Answers (1)

Dmitry  Meshkov
Dmitry Meshkov

Reputation: 931

You can just type

Foo.counter

like

import test.Foo
object Test extends App {
  println(Foo.counter)
}

and

package test
object Foo {
    var counter = 0
}

Your problem is that your object definition is inside class definition. Object is just singleton class in Scala, so your definition is like

class YotascaleCostProcessing extends YotascaleActorSystem{
  class YotascaleCostProcessing$ {
    val INTERNAL_COST_REQUESTS = "internal-cost-requests"
    val INTERNAL_COST_UPDATES = "internal-cost-updates"
  }
  val YotascaleCostProcessing = new YotascaleCostProcessing$()
}

and you can't access to it without instance of YotascaleCostProcessing

Upvotes: 3

Related Questions