# Support \`@switch\` for type-based pattern matches

**URL:** <https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470>\
**Category:** Language Design\
**Created:** [November 26, 2021, 3:18pm UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470 "2021-11-26T15:18:05Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![harpocrates](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/harpocrates/32/2024_2.png) [@harpocrates](https://contributors.scala-lang.org/u/harpocrates)\
**Post date:** [November 26, 2021, 3:18pm UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/1 "2021-11-26T15:18:05Z")

</div>

Java 17 came with a preview of [JEP 406](https://openjdk.java.net/jeps/406). This makes it possible to pattern match based on the type of the scrutinee expression. Looking at the `javap -c` output of these new type-based switches, I see that they work using a [new indy `typeSwitch` bootstrap method](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/runtime/SwitchBootstraps.html) followed by a `tableswitch`. I suspect this is more efficient than the nested `if` strategy used by the Scala compiler.

Given that type-based `match` is quite a bit more widespread in Scala (especially on sealed types), is there any interest/proposal for adopting the (presumably more efficient) compilation strategy that Java uses? Obviously, we’d need to create our own bootstrap method, but I don’t see any reason this wouldn’t be possible…

---

<div class="post-metadata">

**Author:** ![bishabosha](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/bishabosha/32/3101_2.png) [@bishabosha](https://contributors.scala-lang.org/u/bishabosha)\
**Post date:** [November 29, 2021, 9:28am UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/2 "2021-11-29T09:28:55Z")

</div>

It could be the case that the bootstrap method actually is generating a while loop underneath that checks the cases  
e.g.

```java
static String formatterPatternSwitch(Object o) {
    return switch (o) {
        case Integer i -> String.format("int %d", i);
        case Long l -> String.format("long %d", l);
        case Double d -> String.format("double %f", d);
        case String s -> String.format("String %s", s);
        default -> o.toString();
    };
}

```

gets translated to the equivalent of

```scala
def lookup(obj: Any, cases: Array[Class[_]]): Int = {
  val dynCls = obj.getClass
  var i = 0
  while (i < cases.length) {
    if (cases(i).isAssignableFrom(dynCls))
      return i
    i += 1
  }
  return cases.length
}
lookup(foo, Array(classOf[jl.Integer], classOf[jl.Long], classOf[jl.Double], classOf[jl.String])) match {
  case 0 => String.format("int %d", foo.asInstanceOf[jl.Integer])
  case 1 => String.format("long %d", foo.asInstanceOf[jl.Long])
  case 2 => String.format("double %f", foo.asInstanceOf[jl.Double])
  case 3 => String.format("String %s", foo.asInstanceOf[jl.String])
  case _ => foo.toString
}

```

but maybe that could be made an intrinsic of the vm

---

<div class="post-metadata">

**Author:** ![harpocrates](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/harpocrates/32/2024_2.png) [@harpocrates](https://contributors.scala-lang.org/u/harpocrates)\
**Post date:** [November 29, 2021, 2:06pm UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/3 "2021-11-29T14:06:38Z")

</div>

I think the current implementation does effectively translate into a `while` loop, but that’s a hopefully temporary implementation detail. This seems quite similar to the whole indy-fing of string concatenation: by moving the code for handling a high-level construct (`match` in this case) to the runtime you get

- ability to improve the bootstrap method in future Scala releases without breaking binary compatibility
- shorter (due to less boilerplate) bytecode

---

<div class="post-metadata">

**Author:** ![lrytz](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/lrytz/32/1653_2.png) [@lrytz](https://contributors.scala-lang.org/u/lrytz)\
**Post date:** [November 30, 2021, 8:40am UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/4 "2021-11-30T08:40:32Z")

</div>

@dwijnand benchmarked various approaches to encoding class-based matches earlier this year: [https://github.com/scala/scala/pull/9632](https://github.com/scala/scala/pull/9632)

---

<div class="post-metadata">

**Author:** ![hepin1989](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/hepin1989/32/419_2.png) [@hepin1989](https://contributors.scala-lang.org/u/hepin1989)\
**Post date:** [January 19, 2024, 4:03am UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/5 "2024-01-19T04:03:41Z")

</div>

![beff8e22da67c921acb937fadf5dc5bb](https://contributors.scala-lang.org/uploads/default/original/2X/c/ceeac2e45da44be9b6e3ac1004bc446d7cce44f3.jpeg)

I just checked it on my Java application.  
I think this feature is really great

---

<div class="post-metadata">

**Author:** ![hepin1989](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/hepin1989/32/419_2.png) [@hepin1989](https://contributors.scala-lang.org/u/hepin1989)\
**Post date:** [January 6, 2025, 2:38pm UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/6 "2025-01-06T14:38:53Z")

</div>

> **[Java 20 Pattern Matching for Switch: What’s Under the Hood?](https://nataliiadziubenko.com/2023/06/10/pattern-matching.html)**
>
> Pattern matching for switch statements and expressions has evolved as the latest releases unveiled. We can already play with the most exciting changes, such as pattern guards and record patterns, in the Java 19 and 20 preview versions…

Hope Scala will support this out of box.

---

<div class="post-metadata">

**Author:** ![bishabosha](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/bishabosha/32/3101_2.png) [@bishabosha](https://contributors.scala-lang.org/u/bishabosha)\
**Post date:** [January 7, 2025, 8:31am UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/7 "2025-01-07T08:31:04Z")

</div>

not sure this one actually improves performance, because it delegates to a while loop over an array of classes to produce the int that gets switched on

---

<div class="post-metadata">

**Author:** ![tarsa](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/tarsa/32/784_2.png) [@tarsa](https://contributors.scala-lang.org/u/tarsa)\
**Post date:** [January 10, 2025, 11:13pm UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/8 "2025-01-10T23:13:15Z")

</div>

the idea of bootstrap methods it to do heavy lifting on linking time (which is late in java) and then the results are cached and subsequent invocations are cheap.

look at e.g. [JEP 280: Indify String Concatenation](https://openjdk.org/jeps/280) which replaces inline string concatenation with invocation of bootstrap methods. that makes whole thing heavier on first invocation, but also avoids embedding elaborate bytecode directly in application code.

when compilers that output bytecode are producing bytecode for string concatenation, the jvm needs to recognize these bytecode forms and then optimize them knowing the whole thing is about string concatenation, i.e. jvm has special optimizations for string concatenation, but first it must recognize known bytecode sequences that are compatible with such special optimizations. that makes the whole performance optimization quite fragile. opting for invokedynamic / boostrap methods instead allows for future optimizations without worrying if elaborate bytecode sequences in application code get correctly recognized.

similar thing can happen to pattern matching. even if the performance is not improved today compared to inline elaborate bytecode sequences, the performance could be optimized in future jvm versions without changing the application bytecode and without worrying if inline expanded bytecode gets correctly recognized, so special optimizations can apply.

in the end, it’s worth keeping an eye on how java handles pattern matching on class hierarchies in the future. java authors could develop some special optimizations in bootstrap methods for pattern matching, so that would be then beneficial to use also for compiling scala code. for now, let’s use what’s the fastest solution now.

---

<div class="post-metadata">

**Author:** ![bishabosha](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/bishabosha/32/3101_2.png) [@bishabosha](https://contributors.scala-lang.org/u/bishabosha)\
**Post date:** [January 13, 2025, 8:49am UTC](https://contributors.scala-lang.org/t/support-switch-for-type-based-pattern-matches/5470/9 "2025-01-13T08:49:27Z")

</div>

> [@bishabosha](#):
>
> not sure this one actually improves performance, because it delegates to a while loop over an array of classes to produce the int that gets switched on

> [@tarsa](#):
>
> similar thing can happen to pattern matching. even if the performance is not improved today compared to inline elaborate bytecode sequences, the performance could be optimized in future jvm versions without changing the application bytecode and without worrying if inline expanded bytecode gets correctly recognized, so special optimizations can apply.

right i guess the pattern matching bootstrap method might even be intrinsified 🤔
