2

Im attempting to match a List to certain actions, based on the inner elements of the list, specifically, their types:

def car1 = new Car[Racing] {}
def car2 = new Car[Pickup] {}

var myCars = List(car1,car2)

myCars match {

     case Racing :: Pickup => print("your first car is awesome but not your 2nd!"

}

Obviously, the case above is an attempt at pseudocode describing what I'm trying to do, however, it fails.

What is the idiomatic way to match against the types of values that are present in a collection in scala?

2 Answers 2

1

I would create a third class (let's call it CarModel) which both Racing and Pickup extend from and then the following code would work:

def traverseList(list: List[CarModel]): Unit = list match {
  case (raceCar: Racing) :: rest => {
    print("your first car is awesome but not your 2nd!")
    traverseList(rest)
  }
  case (pickUpCar: PickUp) :: rest => {
    doSomethingElse()
    traverseList(rest)
  }
  case Nil => 
}

The above is a recursive example to check each type from the list, but you can use simply the match statement with the list if you wanted to check the first element in the list.

If you want to check the type of your list, as @Naetmul mentioned, you will encounter type erasure. This post explains ways to over come it if you want to verify the type of a list.

Please let me know if you have any questions!

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't the second example suffered from type erasure?
WOW! I just read up on type erasures and it blew my mind away. That's definitely a cool concept I wasn't aware of. Thank you for the cool lesson, and you're absolutely correct, it would suffer from Type Erasures. I guess the two ways of getting around that are using Manifest or ClassTag's as explained thoroughly here: stackoverflow.com/questions/1094173/…
1

Not sure why your using a list if you only have 2 elements - would suggest using a tuple instead. Anyway, I'd do it like this:

myCars match {
  case List((_: Racing), (_: Pickup)) => 
    print("your first car is awesome but not your 2nd!"
}

Note you don't use the cars in your print statement, and threfore I haven't labelled them - rather I've left them as _

3 Comments

This looks valid, but i get: scala.MatchError: List(app.MyClass$$anon$3@2ed053a, app.MyClass$$anon$4@16f22456, app.MyClass$$anon$5@732f95de) (of class scala.collection.immutable.$colon$colon)
It looks like you passed in a list with 3 elements.
thanks. so, i guess this is now a subquestion : stackoverflow.com/questions/25166310 <-- subquestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.