所以我得到了这个特性:
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 }
我还创造了一个延伸Ammo的特质火箭
trait Rockets extends Ammo {
val calibre = Calibre.Rocket
val metric = Metric.Pods
def need(): Unit = Evaluator.getSupplyArray()(4) += difference() }
现在我有一个对象,我希望能够访问火箭的口径
object Evaluator {
def test() = print(Rockets.calibre) //???
但我尝试这种方式不起作用。
答案 0 :(得分:2)
Rockets
是一个特征(同样适用于类),而不是实例(或对象)。
您需要实例化它:
val rocketsInstance = new Rocket {...}
print(rocketsInstance.calibre)
答案 1 :(得分:0)
为简化起见,您可以创建帮助对象,例如:
object Rockets extends Rockets
现在,每次要使用它时都不需要初始化它。只是:
println(Rockets.calibre)