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.
13
+
Sometimes it is necessary to express that the type of an object is a subtype of several other types.
14
+
15
+
In Scala this can be expressed with the help of *intersection types*, (or *compound types* in
16
+
Scala 2) which are types that behave like any part of the intersection.
14
17
15
18
Suppose we have two traits `Cloneable` and `Resetable`:
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`.
66
+
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`.
Note that you can have more than two types: `A with B with C with ...`.
78
+
This means the same as thing as `(...(A with B) with C) with ... )`
79
+
{% endtab %}
80
+
{% tab 'Scala 3' for=compound-types_3 %}
81
+
This intersection type is written in Scala as `Cloneable & Resetable`.
47
82
48
-
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.
49
-
The general form is: `A with B with C ... { refinement }`
<!-- 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. -->
90
+
Note that you can have more than two types: `A & B & C & ...`.
91
+
And `&` is associative, so parentheses can be added around any part without changing the meaning.
92
+
{% endtab %}
93
+
{% endtabs %}
50
94
51
-
An example for the use of refinements is given on the page about [class composition with mixins](mixin-class-composition.html).
95
+
<!--An example for the use of refinements is given on the page about [class composition with mixins](mixin-class-composition.html).-->
0 commit comments