什么是可堆叠修改? [英] What are stackable modifications?

查看:150
本文介绍了什么是可堆叠修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读一本关于Scala的书,并提及使用 traits 可堆叠修改

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?

推荐答案

基本素质区分可堆叠的修改(就像Scala中使用的术语一样)是超级是基于特征如何混合而动态地影响,而一般来说,超级是静态确定的目标。

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.

如果你写

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

然后为Foosuper 将永远是酒吧。

then for Foo "super" will always be Bar.

如果你写

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.

这篇关于什么是可堆叠修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆