匹配字符串数字 - 无法访问的代码

时间:2012-06-24 23:51:32

标签: scala pattern-matching

scala新手,似乎无法使我的匹配表达式工作。我已经读过关于如何评估语句之间的差异(例如,一个新变量而不是一个声明的变量),但似乎无法使反引号或大小写起作用。

// 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"

请帮助澄清为什么这不起作用,因为我在匹配声明的第二行收到“无法访问的代码”错误。我知道这个问题已经结束了,但由于某种原因,我见过的所有例子都没有为我工作。典型的noob语言的东西。谢谢!

1 个答案:

答案 0 :(得分:7)

其中任何一个都可行:

// 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"
}

但是你说你尝试了但它没有用。究竟出了什么问题?