我正试图从Twitter Scala学校开始使用Scala,但我在语法错误方面遇到了麻烦。当我通过我的sbt控制台运行“基础继续”教程http://twitter.github.io/scala_school/basics2.html#match中的模式匹配代码时,编译器会回复“错误:未找到:值&&”。在Scala中有什么改变,以便在编写教程时可能有用,但现在不起作用?涉及的课程是
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))
}
我的副本看起来像这样...
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的用例?
提前致谢。我是新来的。
答案 0 :(得分:3)
如果您按值匹配,就像在您的情况下一样,您不仅可以使用警卫,还可以坚持使用普通模式匹配:
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)
如果要使用模式测试条件,则需要使用guard:
calc match {
case _ if calc.brand == "hp" && calc.model == "20B" => "financial"
...
}
使用_
表示您不需要具体值calc
,而是保护中提到的其他条件。
object && {
def unapply[A](a: A) = Some((a, a))
}
但它不适用于你的具体案例。