I’m practicing my Scala, namely traits, and I’m a bit stuck. I’ve decided to map out the X-men species in Classes and Traits.
I’m stuck on the Power properties. I want a singleton for a List of Power
What I want is basically:
var Rogue = new HomosapienSuperior()
Rogue.addPower("Super Human Strength")
Using addPower will check against the singleton list of Power to see if the power is added, if it isn’t added then throw an exception and tell user to add it to the singleton list of Power first.
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
So I’m thinking of doing:
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?
}
But I don’t know how to refer to the variable in object Power.
My Code so far:
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
}
Note: I haven’t gotten up to the chapters on case classes yet, reading the Programming in Scala 2ed Book from Altima.
Thank you for your time.
To access an object via Class:
Answers provided by agilesteel