Simon Huenecke
Simon Huenecke

Reputation: 97

Use scala trait in scala object

So I got this Trait:

trait Ammo {
val maximum: Int
private var amount: Int = 0
val calibre: Calibre.Value
val metric: Metric.Value

def getAmount(): Int = return amount
def setAmount(i: Int): Unit = amount = i

def need(): Unit

override def toString(): String = return (amount + " " + metric.toString() + " of " + calibre.toString())

def difference(): Int = maximum - amount

def getMaximum(): Int = maximum

def reset() = amount = 0

def incAmount(i: Int) = amount += 1 }

I also created a Trait Rockets that extends Ammo

trait Rockets extends Ammo {
val calibre = Calibre.Rocket
val metric = Metric.Pods

def need(): Unit = Evaluator.getSupplyArray()(4) += difference()  }

Now I have an object in which I want to get access to the calibre of Rockets

object Evaluator {
def test() = print(Rockets.calibre) //???

but the way I try this does not work.

Upvotes: 1

Views: 141

Answers (2)

pme
pme

Reputation: 14803

To simplify things you can create a helper-object, like:

object Rockets extends Rockets

Now you don't need to initialize it every time you want to use it. Just:

println(Rockets.calibre)

Upvotes: 0

V-Lamp
V-Lamp

Reputation: 1678

Rockets is a trait (same would apply for class), not an instance (or Object).

You need to instantiate it:

val rocketsInstance = new Rocket {...}
print(rocketsInstance.calibre)

Upvotes: 2

Related Questions