在 scala 对象中使用 scala trait
Use scala trait in scala object
所以我得到了这个特质:
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
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) //???
但我尝试的方法不起作用。
Rockets
是一个特征(同样适用于 class),而不是实例(或对象)。
您需要实例化它:
val rocketsInstance = new Rocket {...}
print(rocketsInstance.calibre)
为了简化事情,您可以创建一个 helper-object,例如:
object Rockets extends Rockets
现在您不需要每次使用它时都进行初始化。只是:
println(Rockets.calibre)
所以我得到了这个特质:
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
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) //???
但我尝试的方法不起作用。
Rockets
是一个特征(同样适用于 class),而不是实例(或对象)。
您需要实例化它:
val rocketsInstance = new Rocket {...}
print(rocketsInstance.calibre)
为了简化事情,您可以创建一个 helper-object,例如:
object Rockets extends Rockets
现在您不需要每次使用它时都进行初始化。只是:
println(Rockets.calibre)