代码之家  ›  专栏  ›  技术社区  ›  Jim Barrows

从类继承的case类在用作构造函数参数时遇到问题

  •  1
  • Jim Barrows  · 技术社区  · 16 年前

    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类中使用:

    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 回复  |  直到 16 年前
        1
  •  7
  •   sepp2k    16 年前

    错误如下:

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

    因为你定义了 Http 作为一个类,而不是一个对象,你需要做的是 Http() 创建实例。或者更好:定义 首先作为案例对象。