0

I am trying to use strings in a case class like java switch-case statements switch(someString). But scala match statement always resolves to the first block.

whichTopic match {
  case accounts ⇒ {
    logger.info("!!!! ---- FOR ACCOUNTS --- !!! ")

  }
  case users ⇒ {
    logger.info("!!!! ---- FOR USERS --- !!! ")
    // TODO : Handle errors from the consumer
  }
}

Even when whichTopic value has users, it goes into the accounts block

2
  • 3
    case x => will match all input because x is an unbound variable that can hold any value being matched against. case accounts => is the same. You're creating a variable named accounts that can hold (and thus match) any value. Commented Jul 10, 2019 at 5:22
  • ahh...so i was never using the variable to identify which block it has to go to. Thanks for explaining. Commented Jul 10, 2019 at 5:30

2 Answers 2

3

It's because you didn't use it correctly - what you actually did is 2 cases of "alias" the whichTopic variable to accounts or users variables, but didn't specify what is "special" about them.

You should do something like:

whichTopic match {
  case accounts if accounts.startsWith("accounts") => logger.info("!!!! ---- FOR ACCOUNTS --- !!! ")
  case users if users.startsWith("users") => logger.info("!!!! ---- FOR USERS --- !!! ")
}

This is a case to check if is the strings start with accounts or users.

Of course, you can replace startsWith with any string method you want - like contains or something else which suits your case.

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

Comments

3

ahh...so i was never using the variable to identify which block it has to go to.

If you want to check equality to an existing variable, you can write

case x if x == accounts => ...

(as in Gal Naor's answer) or

case `accounts` => ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.