Reputation: 7504
Moving to Scala from Java, one sees usage of pattern matching for branching out the code, something achieved with if-else in Java. But Scala offers if-else too.
Going by code readability, I personally prefer if-else. Also, google search tells that bytecode generated for pattern matching is much bigger.
So under what circumstances one should prefer one over other?
Upvotes: 1
Views: 1277
Reputation: 40500
Pattern matching is much more powerful than if/else
, and than java's switch
statement.
You can elegantly check object types with it:
foo match {
case i: Int => i
case f: Double => Math.round(f*100)
case s: String => s.toInt
}
You can deconstruct complex objects:
foo match {
case SomeObject(AnotherObject(_, _, bar), _, _, baz) => bar -> baz
case head :: tail => head -> tail
case Seq(a, b, c, _, _ rest@_*) => (a,b,c) -> rest
}
You can use custom matchers and deconstructors by implementing unapply
and unapplySeq
:
foo match {
case PrimeNumber(next, _@_*) => print(s"$foo is prime, next is $next")
case Compound(primes@_*) => print(s"$foo is compound: ${primes.mkString("*")}=$foo"
}
You can use them as a shortcut declaring a partial function to deconstruct parameters:
stuff.zipWithIndex.collect { case (foo, idx) if idx % 2 == 0 => foo }
Etc. (many, may uses). I am not sure about the size of the byte code ... and frankly, don't know why I would care. In cases where these kinds of differences in size matter, I would probably be writing "C" or assembly anyway.
Upvotes: 4
Reputation: 27356
Java also offers switch
so a similar question arises in Java as well. Your personal preference for switch
vs if
in Java will help inform the choice of match
vs if
in Scala.
Scala match
allows the following:
If you don't need any of these, then if
is probably a better choice.
Also remember that the size of the bytecode is not a great measure of performance because any code where performance matters will be JIT compiled into native code.
Upvotes: 2