mardi 15 mars 2016

How does stackable pattern, in Scala, apply when you need more parameters

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:

  1. Add method putMultiplied to new trait MultiplyX

    trait 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 putMultiplied method

  2. 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 constant before 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?

[1] http://ift.tt/1bNrpvU

Aucun commentaire:

Enregistrer un commentaire