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

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 (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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.