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 に答える