关于scala:匹配类成员“错误:找不到:值&&”

Matching on class members “error: not found: value &&”

我正试图从Twitter Scala School开始进入Scala,但是在语法错误方面遇到了麻烦。 当我通过sbt控制台从"基础继续"教程http://twitter.github.io/scala_school/basics2.html#match运行"模式匹配"代码时,编译器使我回到"错误:找不到:值&&" 。 Scala中的某些内容发生了变化,以适应编写本教程时可能有效但现在不起作用的东西吗? 涉及的课程是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Calculator(pBrand: String, pModel: String) {
  /**
   * A constructor
   */

  val brand: String = pBrand
  val model: String = pModel
  val color: String = if (brand.toUpperCase =="TI") {
   "blue"
  } else if (brand.toUpperCase =="HP") {
   "black"
  } else {
   "white"
  }

  // An instance method
  def add(m: Int, n: Int): Int = m + n
}

class ScientificCalculator(pBrand: String, pModel: String) extends Calculator(pBrand: String, pModel: String) {
  def log(m: Double, base: Double) = math.log(m) / math.log(base)
}

class EvenMoreScientificCalculator(pBrand: String, pModel: String) extends ScientificCalculator(pBrand: String, pModel: String) {
  def log(m: Int): Double = log(m, math.exp(1))
}

我的代表看起来像这样...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bobk-mbp:Scala_School bobk$ sbt console
[info] Set current project to default-b805b6 (in build file:/Users/bobk/work/_workspace/Scala_School/)
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.9.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_17).
Type in expressions to have them evaluated.
Type :help for more information.
...
scala> def calcType(calc: Calculator) = calc match {
     |   case calc.brand =="hp" && calc.model =="20B" =>"financial"
     |   case calc.brand =="hp" && calc.model =="48G" =>"scientific"
     |   case calc.brand =="hp" && calc.model =="30B" =>"business"
     |   case _ =>"unknown"
     | }
<console>:9: error: not found: value &&
         case calc.brand =="hp" && calc.model =="20B" =>"financial"
                                 ^
<console>:10: error: not found: value &&
         case calc.brand =="hp" && calc.model =="48G" =>"scientific"
                                 ^
<console>:11: error: not found: value &&
         case calc.brand =="hp" && calc.model =="30B" =>"business"
                                 ^
scala>

在对类成员进行匹配时,如何在我的案例中获取AND的用例?

提前致谢。 我是新来的。


如果您按情况进行值匹配,则不仅可以使用防护,还可以坚持纯模式匹配:

1
2
3
4
5
6
def calcType(calc: Calculator) = (calc.brand, calc.model)  match {
     case ("hp","20B") =>"financial"
     case ("hp","48G") =>"scientific"
     case ("hp","30B") =>"business"
     case _             =>"unknown"
}

我发现这更容易解析。


当您想使用模式测试条件时,则需要使用防护:

1
2
3
4
calc match {
  case _ if calc.brand =="hp" && calc.model =="20B" =>"financial"
  ...
}

使用_表示您不必担心calc具有的具体值,而不必担心防护中提到的某些其他情况。

顺便说一句,可以写一个合取器:

1
2
3
object && {
  def unapply[A](a: A) = Some((a, a))
}

但这在您的具体情况下不起作用。