Mandroid
Mandroid

Reputation: 7504

Scala: Pattern matching vs if-else

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

Answers (2)

Dima
Dima

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

Tim
Tim

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:

  1. Multiple tests on the same value
  2. Testing type and structure as well as value
  3. Extraction of values during the test
  4. Cleaner and more readable code

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

Related Questions