What are stackable modifications?

2019-04-06 15:11发布

问题:

I've been reading a book about Scala and there's mention of stackable modifications using traits. What are stackable modifications and for what purposes are they meant to be used?

回答1:

The fundamental quality which distinguishes stackable modifications (as the terminology is used in scala anyway) is that "super" is influenced dynamically based on how the trait is mixed in, whereas in general super is a statically determined target.

If you write

abstract class Bar { def bar(x: Int): Int }
class Foo extends Bar { def bar(x: Int) = x }

then for Foo "super" will always be Bar.

If you write

trait Foo1 extends Foo { abstract override def bar(x: Int) = x + super.bar(x) }

Then for that method super remains unknown until the class is made.

trait Foo2 extends Foo { abstract override def bar(x: Int) = x * super.bar(x) }

scala> (new Foo with Foo2 with Foo1).bar(5)
res0: Int = 30

scala> (new Foo with Foo1 with Foo2).bar(5)
res1: Int = 50

Why is this interesting? An illustrative example might be some data which you want to compress, encrypt, and digitally sign. You might want to compress then encrypt then sign, or you might want to encrypt then sign then compress, etc. If you design your components in this way, you can instantiate a customized object with exactly the bits you want organized the way you want.



回答2:

I looked at Real-World Scala presentation where the term stackable modifications is also used. Apparently it's traits that call the super method when overriding, essentially adding functionality and not replacing it. So you accumulate functionality with traits, and it can be used where in Java we often use aspects. Trait plays the role of an aspect, overriding the "interesting" methods and adding the specific functionality such as logging etc. and then calling super and "passing the ball" to the next trait in the chain. HTH.