The author mentions a syntax (A with B) which I’m not familiar with. Is this something the author is introducing in the blog post, or is it a feature already provided by Scala, or perhaps Scalaz? The author intends it to be an intersection type.
I’m familiar already with some other languages which support union and intersection types, and I’m trying to understand what Scala supports and does not.
The A with B syntax is standard Scala syntax for intersection types. Note that with is not commutative, so A with B is not the same type as B with A. (this will be replaced in Scala 3)
Union types are not supported directly in Scala 2.x, but libraries like Scalaz provide them (in a similar way like in the blog post) and Scala 3 will also have them.
Thanks for the explanation. So I’m not sure what it means for an intersection to not be commutative? If its not commutative, then it’s not really an intersection. Right?
What are the elements of the type A with B, and what are the instances of B with A?
Or does the concept even exist in Scala: “elements of a type” ?
I’m not the expert, but I believe that’s correct. Note that this is changing in Scala 3, which is replacing the old with types with true intersection types and union types.
It is commutative when used purely as a type. When used in an extends clause, you can get different implementations.
Every object that is of type A with B is also of type B with A and vice versa, hence A with B is the same type as B with A.
If, however, both A and B define the same member, then in an extends clause the last one wins. This kind of implementation resolution is known as linearization.
**Welcome to Scala 2.12.4 (OpenJDK 64-Bit Server VM, Java 1.8.0_181).
Type in expressions for evaluation. Or try :help.
trait A { def greet: Unit = println(“Hello!”) }
defined trait A
trait B { def greet: Unit = println(“Yo!”) }
defined trait B
class C extends A with B { override def greet: Unit = super.greet }
defined class C
class D extends B with A { override def greet: Unit = super.greet }
defined class D
That Scala 3 will support true intersection and union types (but apparently not complementary types) is very interesting. Has this been presented at as a conference or journal paper? I’d love to use this citation in my thesis.