You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
15
16
16
17
Suppose we have two traits `Cloneable` and `Resetable`:
17
18
18
19
```tut
19
20
trait Cloneable extends java.lang.Cloneable {
20
-
override def clone(): Cloneable = {
21
+
override def clone(): Cloneable = {
21
22
super.clone().asInstanceOf[Cloneable]
22
23
}
23
24
}
@@ -26,27 +27,15 @@ trait Resetable {
26
27
}
27
28
```
28
29
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.
30
31
31
32
```
32
-
def cloneAndReset(obj: ?): Cloneable = {
33
+
def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {
33
34
val cloned = obj.clone()
34
35
obj.reset
35
36
cloned
36
37
}
37
38
```
39
+
Because the type of `obj` is `Cloneable with Resetable`, we know the object has both a `clone` and a `reset` method.
38
40
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