0

How to perform pattern matching for multiple types in scala ?

I am looking to achieve something like below where pattern match type of a and b and execute the code for the combination of type.

def equals[T](a: T, b: T) = {
    (a,b) match {
        case (a,b) : (String, String) = isEquals(a.asInstanceOf[String],b.asInstanceOf[String])
        case (a,b) : (Int, Int) = isEquals(a.asInstanceOf[Int],b.asInstanceOf[Int])  
    }
}

1 Answer 1

3

You were very close:

def equals[T](a: T, b: T) =
  (a, b) match {
    case (a: String, b: String) => println(s"Strings: $a $b")
    case (a: Int, b: Int)       => println(s"Ints: $a $b")
    case _                      => println("Not sure what")
  }

equals("foo", "bar") // Strings: foo bar
equals(12, 34)       // Ints: 12 34
equals(true, false)  // Not sure what
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much Slouc.. You saved my time.. I did not find this syntax online.. Can you recommend any website or material where can i look for Scala syntax in general in case of clarification which would save time..
No problem. Just one thing: when asking a question on SO, it is very useful to provide a MCV example, which makes it both easier for you to reason about your problem, and for other users to answer it. For example, see how I used println instead of your isEquals; that's because isEquals has nothing to do with the problem itself. Regarding resources, when I was starting out I liked this book and this course.
Also, when you get an answer that helped you solve your problem, established practice is to simply mark the answer as resolved. This way you're saying "yes, this is exactly what I needed", so you don't even have to write "thanks" etc. in the comments. And the person who answered it gets a sense of completion that way, along with some reputation points. That's all. Enjoy your time on SO!

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.