Skip to content

Instantly share code, notes, and snippets.

@szegedi
Last active October 4, 2018 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szegedi/477b8030d1bfab33cc6d44a78d9396f4 to your computer and use it in GitHub Desktop.
Save szegedi/477b8030d1bfab33cc6d44a78d9396f4 to your computer and use it in GitHub Desktop.
Scala boolean pattern matching

TL;DR: scalac apparently doesn't believe in exhaustiveness of value set (true, false) for a boolean, so pattern matching on a boolean in Scala emits a branch for "neither true nor false". (I won't even go into it emitting comparison to 1 and 0 instead of using ifeq or ifne instructions, or those gotos that jump to the very next instruction.)

This scala code:

final class X {
  final def foo(b: Boolean) = 
    b match {
      case true  => 10
      case false => 11
    }
}

after treated with javap:

scalac X.scala
javap -c -p X

shows:

  public final int foo(boolean);
    Code:
       0: iload_1
       1: istore_3
       2: iconst_1
       3: iload_3
       4: if_icmpne     13
       7: bipush        10
       9: istore_2
      10: goto          42
      13: goto          16
      16: iconst_0
      17: iload_3
      18: if_icmpne     27
      21: bipush        11
      23: istore_2
      24: goto          42
      27: goto          30
      30: new           #13                 // class scala/MatchError
      33: dup
      34: iload_3
      35: invokestatic  #19                 // Method scala/runtime/BoxesRunTime.boxToBoolean:(Z)Ljava/lang/Boolean;
      38: invokespecial #23                 // Method scala/MatchError."<init>":(Ljava/lang/Object;)V
      41: athrow
      42: iload_2
      43: ireturn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment