0

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"

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

4

1 回答 1

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

但是你说你试过了,没用。那么,究竟出了什么问题呢?

于 2012-06-25T00:21:25.480 回答