Skip to content

Commit 751fd1d

Browse files
committed
Rewrote compound types tour
1 parent c5e811c commit 751fd1d

File tree

1 file changed

+7
-18
lines changed

1 file changed

+7
-18
lines changed

tutorials/tour/_posts/2017-02-13-compound-types.md

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,16 @@ categories: tour
99
num: 24
1010
next-page: explicitly-typed-self-references
1111
previous-page: abstract-types
12+
prerequisite-knowledge: traits, unified-types, mixin-class-composition
1213
---
1314

14-
Sometimes it is necessary to express that the type of an object is a subtype of several other types. In Scala this can be expressed with the help of *compound types*, which are intersections of object types.
15+
Sometimes it is necessary to have parameter has multiple supertypes. In Scala this can be expressed with the help of _compound types_, which are intersections of object types.
1516

1617
Suppose we have two traits `Cloneable` and `Resetable`:
1718

1819
```tut
1920
trait Cloneable extends java.lang.Cloneable {
20-
override def clone(): Cloneable = {
21+
override def clone(): Cloneable = {
2122
super.clone().asInstanceOf[Cloneable]
2223
}
2324
}
@@ -26,27 +27,15 @@ trait Resetable {
2627
}
2728
```
2829

29-
Now suppose we want to write a function `cloneAndReset` which takes an object, clones it and resets the original object:
30+
Now suppose we want to write a function `cloneAndReset` which takes an object, clones it and resets the original object. We use the keyword `with` to specify that the object must be a subtype of both types.
3031

3132
```
32-
def cloneAndReset(obj: ?): Cloneable = {
33+
def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {
3334
val cloned = obj.clone()
3435
obj.reset
3536
cloned
3637
}
3738
```
39+
Because the type of `obj` is `Cloneable with Resetable`, we know the object has both a `clone` and a `reset` method.
3840

39-
The question arises what the type of the parameter `obj` is. If it's `Cloneable` then the object can be `clone`d, but not `reset`; if it's `Resetable` we can `reset` it, but there is no `clone` operation. To avoid type casts in such a situation, we can specify the type of `obj` to be both `Cloneable` and `Resetable`. This compound type is written like this in Scala: `Cloneable with Resetable`.
40-
41-
Here's the updated function:
42-
43-
```
44-
def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {
45-
//...
46-
}
47-
```
48-
49-
Compound types can consist of several object types and they may have a single refinement which can be used to narrow the signature of existing object members.
50-
The general form is: `A with B with C ... { refinement }`
51-
52-
An example for the use of refinements is given on the page about [abstract types](abstract-types.html).
41+
Compound types can consist of several object types. The general form is: `A with B with C ...`.

0 commit comments

Comments
 (0)