2

In the following:

argument match { 
  case A => **executed code**
  ...

is the executed code directly link at compile time with respect to the pattern of the matched argument, or is it "simply" some kind of powerful switch-case solved at runtime?

(I'm speaking about off line compilation, not JIT)

Edit: answer

The question was close as duplicate. I think this answer would have been wiser:

The question How is pattern matching in Scala implemented at the bytecode level? explain that pattern matching is converted to a set of if and else, chosen depending on the patterns.

Thus it is not solved at compile time, in the sense that:

  • the compiler does not link directly to the **executed code**, w.rt the argument type
  • thus, the matching (i.e. the if-else) is computed at runtime

(I hoped it did because I'm pretty sure it could in at least some situation)

Also, looking at the question is it possible to remove jumps with final boolean on java jit?, it is possible that the JIT will actually do it. Not sure how well it works in practice (I would expect it depends on the situation), but if it does, then processing pattern matching at compile time is not really necessary.

Community
  • 1
  • 1
Juh_
  • 14,628
  • 8
  • 59
  • 92
  • I don' t completely agree with the *duplicate question* mark (but I don't completely disagree neither). The other question is not the same but it answers the question indirectly. I'll add the answer I would have expected in the question. – Juh_ Aug 20 '15 at 13:16
  • 1
    If you're sure that you can resolve a pattern match at compile time, you can use a macro to do exactly that. – Apocalisp Aug 20 '15 at 14:17
  • I didn't know about macro in scala. I'll be looking into it (I found that: http://docs.scala-lang.org/overviews/macros/overview.html) – Juh_ Aug 20 '15 at 16:34

1 Answers1

2

Scalac will compile a pattern match to either a switch (http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10) or a series of if/else statements.

Apocalisp
  • 34,834
  • 8
  • 106
  • 155