match with string numbers - unreachable code

久未见 提交于 2019-12-09 03:56:55

问题


New to scala, and can't seem to get my match expression to work. I've read about the differences between how the statement is evaluated (e.g. a new variable as opposed to one declared), but can't seem to get backticks or capitalization to work.

// declared inside of object
val numberOne = "+17201234567"
val numberTwo = "+17201235678"

def returnSomething(number: String): String = number match {
  case numberOne => "my first number"
  case numberTwo => "my second number"
  case _ => "a default number"
}

...

returnSomething("+17201235678") // should return "my second number"

Please help clarify why this isn't working, as I get an "unreachable code" error at the second line of the match statement. I know this question is all over, but for some reason none of the examples I've seen work for me. Typical noob language stuff. Thanks!


回答1:


Either of these would work:

// declared inside of object
val numberOne = "+17201234567"
val numberTwo = "+17201235678"

def returnSomething(number: String): String = number match {
  case `numberOne` => "my first number"
  case `numberTwo` => "my second number"
  case _ => "a default number"
}


// declared inside of object
val NumberOne = "+17201234567"
val NumberTwo = "+17201235678"

def returnSomething(number: String): String = number match {
  case NumberOne => "my first number"
  case NumberTwo => "my second number"
  case _ => "a default number"
}

But you said you tried and it did not work. So, what exactly went wrong?



来源:https://stackoverflow.com/questions/11182105/match-with-string-numbers-unreachable-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!