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

Jim*_*ows 1 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") {}
Run Code Online (Sandbox Code Playgroud)

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

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

然后尝试在这里使用:

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

为此我得到以下莫名其妙的编译器错误:

[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)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

sep*_*p2k 7

错误在这里:

Url(Http, None, None, localhost, None, None, None)
    ^^^^
Run Code Online (Sandbox Code Playgroud)

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

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