0

我希望了解以下 Scala 代码生成的编译时错误:

class MyClass {
    def determineType(x:Any):String = {
        x match {
            case Int => "It's an int."
            case Float => "It's a Float."
            case CIn  => "It's a CIn without a specifier."
            case c:CIn => "It's a CIn with a specifier."
            case DIn=> "It's a DIn without a specifier." // Error:Cannot resolve symbol DIn
            case d:DIn=> "It's a DIn with a specifier."
            case _ => "It's something else."
        }
    }
    case class CIn()
    class DIn
} // End class definition

def determineType(x:Any):String = {
    x match {
        case Int => "It's an int"
        case Float => "It's a Float"
        case COut  => "It's a COut without a specifier." // Error: Wrong forward reference
        case c:COut => "It's a COut with a specifier."
        case DOut=> "It's a DOut without a specifier." // Error: Cannot resolve symbol DOut.
        case d:DOut=> "It's a DOut with a specifier."
        case _ => "It's something else."
    }
}

case class COut()
class DOut()

determineType在within的版本中MyClass,thecase class CIn和正则class DIn都在 after 之后定义和声明determineType。尝试匹配DIn没有说明符变量的 a 时会生成符号解析错误。

在脚本范围内,我们同样定义了 acase class Cout和一个正则class DOut。在脚本范围版本中,determineType我们有两个不同的错误。第一个是在引用没有说明符的case class类型 ( Cout) 时生成的,它显示为“错误的前向引用”。第二个是在引用不带说明符的常规class类型 ( DOut) 时生成的,它是符号解析错误。

我是该语言的新手,因此不确定为什么在case语句中包含说明符会影响处理前向引用的方式。

4

1 回答 1

2

如果您编写 match 子句case Foo =>,则匹配的不是类型(或类)Foo而是 Foo。所以case Int =>不匹配整数值,并且因为没有值(或对象)不起作用。case DIn =>DIn

以下作品:

val Foo = 1
object Bar

def testVal(x: Any) = x match {
  case Foo => "it's Foo"
  case Bar => "it's Bar"
  case _   => "none of the above"
}

testVal(1)  // Foo!
testVal(Bar) // Bar
testVal(Foo + 1) // none

如果您想匹配类的实例,则需要匹配子句case b: Baz =>case _: Baz(如果您对将实例绑定到值不感兴趣)。对于案例类,您可以进一步使用自动提供的提取器,因此case class Baz()您也可以匹配 as case Baz() =>Baz当包含特此提取的参数时,这通常更有意义:

case class Baz(i: Int)

def testType(x: Any) = x match {
  case Baz(3) => "Baz with argument 3"
  case b: Baz => "Baz with argument other than 3"
  case Baz    => "Baz companion!"
  case _      => "none of the above"
}

testType(Baz)     // companion object!
testType(Baz(3))
testType(Baz(4))

案例类还为您提供了伴侣object,因此您可以在此处实际使用case Baz =>. Anobject是一种值。


最后,我不知道您使用的是哪个 Scala 版本,但在常规的当前 Scala 中,您不能省略matchRHS 定义的关键字determineType

def determineType(x: Any): String = {
  case _ => "anything"
}
<console>:53: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: String
          def determineType(x: Any): String = {
                                              ^

你必须写:

def determineType(x: Any): String = x match /* ! */ {
  case _ => "anything"
}
于 2015-10-29T10:38:59.653 回答