An example of the syntax of Intersection Types in Scala 3 (Dotty)

UPDATE: As a more recent example, see my free “Scala 3 Intersection Types” video.

As a brief note to self, here’s an early example of the syntax of Intersection Types in Scala 3 (Dotty):

trait A:
    def a = "a"

trait B:
    def b = "b"

trait C:
    def c = "c"

object Main {

    def foo(d: A & B & C): Unit =
        println(d.a)
        println(d.b)
        println(d.c)

    def main(args: Array[String]): Unit =
        class D extends A with B with C
        val d = new D
        foo(d)

}

There’s much more to say about intersection types, but I just want to start today by showing this syntax:

def foo(d: A & B & C) ...
        ------------

A few notes about intersection types (&) vs. with:

  • A & B replaces A with B
  • & is commutative (conversely, order is important with with)
    • A with B is different than B with A
    • A & B is the same as B & A

I’ll write more about intersection types in the future, but for now you can learn more on this Dotty page. (That link is broken for now; hopefully they’ll get that page back up.)