- Learn Scala Programming
- Slava Schmidt
- 358字
- 2021-06-10 19:35:44
Compound (intersection) types
A compound type is defined as a combination of zero or more component types with a refinement. If no refinement is provided, an implicit empty one ({}) is added by the compiler. Depending on the number of components, we can have the following cases:
- If just a refinement is given, the compound type is equivalent to extending AnyRef
- A single type is extended by using the corresponding extends keyword
- Two or more types are combined by interleaving them with the with keyword
In the case of a name clash in combined types and/or refinement, the usual override rules apply. This means that the rightmost type or refinement has the highest priority. This combination also represents an inheritance relation, and it is possible to access members of extended types with the use of the super keyword.
The compound type is easy to imagine as a layer of wrappers. Because of this, the process of resolving conflicting members in traits is called trait linearisation, while the decorator design pattern is called stackable traits. The following example demonstrates how layers of traits can access methods defined on subtypes of the compound type to implement a decorated toString representation:
scala> trait A { override def toString = "A" }
defined trait A
scala> trait B { override def toString = super.toString + "B" }
defined trait B
scala> trait C { override def toString = super.toString + "C" }
defined trait C
scala> class E extends A with B with C {
| override def toString: String = super.toString + "D"
| }
defined class E
scala> new E().toString
res28: String = ABCD
The definition of type contains just a refinement in the case of zero components being extended. This way of defining a type is known as a structural type. The use of structural types is generally discouraged in Scala because it can lead to a generation of bytecode that will access structurally defined members using reflection, which is significantly slower. Nevertheless, it is useful to define type lambdas, which we will take a look at near the end of this chapter.
- 數(shù)據(jù)庫系統(tǒng)教程(第2版)
- C# 2012程序設(shè)計實踐教程 (清華電腦學(xué)堂)
- Python程序設(shè)計(第3版)
- Java Web開發(fā)技術(shù)教程
- Elasticsearch for Hadoop
- 第一行代碼 C語言(視頻講解版)
- C#開發(fā)案例精粹
- 持續(xù)輕量級Java EE開發(fā):編寫可測試的代碼
- C#程序設(shè)計(項目教學(xué)版)
- Developing SSRS Reports for Dynamics AX
- Mastering AWS Security
- Python Social Media Analytics
- C語言程序設(shè)計與應(yīng)用實驗指導(dǎo)書(第2版)
- 深入實踐C++模板編程
- Java程序性能優(yōu)化實戰(zhàn)