1

我有这个案例类定义:

class Protocol(protocol:String) 

object Protocol {
    def apply(protocol:String) :Protocol = {
      protocol.toUpperCase match {
        case "HTTP" => Http()
        case "HTTPS" => Https()
        case "Ftp" => Ftp()
        case "Mail" =>Mail()
        case other => new Protocol(other)
    }
}
}

case class Http() extends Protocol("HTTP") {}

然后我在这个案例类中使用它:

case class Url(protocol: Protocol,
  username: Option[String],
  password: Option[String],
  domainName: DomainName,
  port: Option[Int], 
  path: Option[List[String]], 
  parameters: Option[List[Parameter]]) {

然后尝试在这里使用:

"An url class" should {
    "represent http://localhost" in {
        val url = Url(Http, None, None, localhost, None, None, None)
            url.toString must beEqualTo("http://localhost")
    }

为此,我得到以下令人费解的编译器错误:

[error] C:\Users\Jim.Barrows\Desktop\workspaces\utils\src\test\scala\UrlSpec.scala:16: type mismatch;
[error]  found   : bizondemand.utils.models.internet.Http.type (with underlying type object bizondemand.utils.models.internet.Http)
[error]  required: bizondemand.utils.models.internet.Protocol
[error]                         val url = Url(Http, None, None, localhost, None, None, None)

我究竟做错了什么?

4

1 回答 1

7

错误在这里:

Url(Http, None, None, localhost, None, None, None)
    ^^^^

由于您定义Http为类,而不是对象,因此您需要Http()创建一个实例。甚至更好:Http首先定义为案例对象。

通常首选使用案例对象而不是没有参数的案例类。

于 2010-07-06T22:23:47.287 回答