Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching or isInstanceOf in Scala

Suppose I have the following class hierarchy:

trait A; class A1 extends A; class A2 extends A

Now I need to filter A1 instances in List[A]. I use either pattern matching or isInstanceOf.

 as.filter(cond(_){case _: A1 => true}) // use pattern matching
 as.filter(_.isInstanceOf[A1]) // use isInstanceOf

Does it work the same ? What would you prefer ?

like image 371
Michael Avatar asked Aug 27 '14 15:08

Michael


People also ask

Does Scala have pattern matching?

Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.

Which method of case class allows using objects in pattern matching?

The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches.

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .

How do you write a match case in Scala?

Using if expressions in case statements i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + a) case c if 20 to 29 contains c => println("20-29 range: " + a) case _ => println("Hmmm...") }


1 Answers

Why don't you use collect? That has the added benefit that the returned list will be of the right type (List[A1] instead of List[A])

val a1s = as.collect { case x:A1 => x }
like image 141
Rüdiger Klaehn Avatar answered Sep 26 '22 02:09

Rüdiger Klaehn