我对scala真的很陌生。我试图从类外部访问一个伴侣类变量。如果可能的话,如何在不创建类的实例的情况下如何执行此操作。
在以下示例中,我可以从YotascaleCostProcessing类中访问INTERNAL_COST_REQUESTS
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)
}
}
当我从另一个包中的另一个类做YotascaleCostProcessing.INTERNAL_COST_UPDATES时,我收到一个错误" not found:value YotascaleCostProcessing"即使YotascaleCostProcessing的导入存在。这种方法的唯一方法就是当我这样做时:新的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)
}
}
答案 0 :(得分:3)
您只需输入
即可Foo.counter
像
import test.Foo
object Test extends App {
println(Foo.counter)
}
和
package test
object Foo {
var counter = 0
}
您的问题是您的对象定义在类定义中。对象只是Scala中的单例类,因此您的定义类似于
class YotascaleCostProcessing extends YotascaleActorSystem{
class YotascaleCostProcessing$ {
val INTERNAL_COST_REQUESTS = "internal-cost-requests"
val INTERNAL_COST_UPDATES = "internal-cost-updates"
}
val YotascaleCostProcessing = new YotascaleCostProcessing$()
}
如果没有YotascaleCostProcessing
的实例,则无法访问它