Dotty is the new Scala compiler that is written in Scala 2 and it will be future Scala i.e Scala 3.0. The current version of Dotty is 0.24.0-RC1 and very soon the first stable version will be launched in the market.
Dotty is completely open source and it is available on GitHub.
With this blog, I am going to share you one of New Types that Dotty is coming up with: Intersection Type
An Intersection Type combine multiple types into one which has all the features of the individual types combined. You need to use ampersand
& operator to combine the multiple types (like
A & B).
Earlier in Scala 2, these were used as compound types
A with B. Although, you can still make use of with keyword in Dotty, but internally it is interpreted as
& and in future releases of Dotty,
with keyword will be deprecated and removed.
Intersection Types in Dotty are commutative which means that
A & B is same types as
B & A, they both will hold the same values.
Example of Dotty’s Intersection Types –
You can find the complete example of Dotty Intersection Type from here.
In the example, there are two traits namely:
And both the traits have common method
whoAmI which is unimplemented. It means that any class who inherits these traits will have to provide the concrete implementation.
And there are two concrete classes using the above traits, which are:
Both the classes are Intersection of the two traits (
ErrorHandling). And both of the concrete classes have implementation of method
whoAmI. In both of them, its type is the intersection of
And finally there is a handler method, which will act on the
ResponseData & ErrorHandling intersection type. The method will return optional string as either data or error code.
The important thing to note here in this example, both the ampersand
with keyword are used. And there is a reason for that.
You can not declare a class/trait with
& keyword. This means, writing
class A extends B & C is not a valid statement in Dotty. You still need to use
with keyword here. But it will be deprecated in the future releases.
Key Takeaways –
- To create an instance containing both the types, one need to use
withkeyword for inheriting multiple traits.
A & Bis the same type as
B & A.
- You can use
&while defining a new type like
type P = ResponseData & ErrorHandling.
And then you can also use this type in method calls or pattern matching.