我正在练习我的Scala,即特质,我有点卡住了。我决定在类和特征中绘制X-men物种。
我坚持使用Power属性。我想要一个单一的力量列表
我想要的基本上是:
var Rogue = new HomosapienSuperior()
Rogue.addPower("Super Human Strength")
使用addPower将检查Power的单例列表以查看是否添加了电源,如果未添加电源则抛出异常并告诉用户先将其添加到Power的单例列表中。
object Power {
val powers = new HashMap[String, String] // power -> description, list of Power!
val secondaryPowers = new HashMap[String, String] // "Fly" -> "Can fly"
}
import Power._
import scala.collection.mutable.HashMap
class Power(power: String) {
//How do I refer to the object/singleton Power list?
}
abstract class Homosapien {
def name:HashMap[String, String]
def sex: Sex
}
class HomosapienSuperior(
val name:HashMap[String, String],
val sex:Sex,
val power: Power
) extends Homosapien
所以我正在考虑这样做:
class Power(power: String) {
var power = List[String]
def addPower(power: String): List = {
//check the object Power.powers(power)
// if not in the object Power throw exception else
// new list (power) prepend this.power
}
//How do I refer to the object/singleton Power list?
}
但我不知道如何引用对象Power中的变量。
我的代码到目前为止:
object Sex extends Enumeration {
type Sex = Value
val male = Value("male")
val female = Value("female")
val other = Value("other")
}
object Power {
val powers = new HashMap[String, String] // power -> description
val secondaryPowers = new HashMap[String, String]
}
import Sex._
import Power._
import scala.collection.mutable.HashMap
class Power(power: String) {
}
abstract class Homosapien {
def name:HashMap[String, String]
def sex: Sex
}
class HomosapienSuperior(
val name:HashMap[String, String],
val sex:Sex
/*
val power:HashMap[String, String],
val secondaryPower:HashMap[String, String] */
) extends Homosapien with power with secondaryPower
class HomosapienSuperiorSuperior(
val name:HashMap[String, String],
val sex:Sex
//val power:HashMap[String, String]
) extends Homosapien with power
trait power {
val power = List[Power] //power name and description
}
trait secondaryPower {
val secondaryPower = List[Power] //power name and description
}
注意:我还没有完成关于案例类的章节,阅读Altima的Scala 2ed Book编程。
感谢您的时间。
答案 0 :(得分:1)
通过Class访问对象:
Power.powers
agilesteel提供的答案