Following the canonical example for stackable traits[1]:
trait Double extends IntQueue {
abstract override def put(x: Int) { super.put(2 * x) }
}
What if I wanted the constant '2' to be set dymically?
I have two solutions but with rather big downsides:
-
Add method
putMultipliedto new traitMultiplyXtrait Multiplier extends IntQueue { abstract override def putMultiplied(constant: Int, x: Int) { super.put(constant * x) } }However this destroys the stackable property, because another stackable trait would have to know the
putMultipliedmethod -
Make a setter for the constant:
trait Multiplier extends IntQueue { var constant //hihi a variable constant abstract override def put(x: Int) { super.put(constant * x) } }However this seems weird, and puts the burden on the caller to remember to set
constantbefore every invocation.
Intuitively I would want the trait to have a constructor parameter:
trait Multiplier(val constant: Int) extends IntQueue {
abstract override def put(x: Int) { super.put(constant * x) }
}
But alas we all know traits do not support parameters.
Am I asking too much of this pattern in combination with Scala traits? How would this be solved?
Aucun commentaire:
Enregistrer un commentaire