继承自类的case类正在将问题用作构造函数参数

时间:2010-07-06 22:15:32

标签: scala case-class

我有这个案例类定义:

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)

我做错了什么?

1 个答案:

答案 0 :(得分:7)

错误在于:

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

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

通常首选使用case对象而不是不带参数的case类。