从类继承的案例类在用作构造函数参数时存在问题
我有这个案例类定义:
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)
我做错了什么?
I have this case class define:
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") {}
Which I then use in this case class:
case class Url(protocol: Protocol,
username: Option[String],
password: Option[String],
domainName: DomainName,
port: Option[Int],
path: Option[List[String]],
parameters: Option[List[Parameter]]) {
And then try to use here:
"An url class" should {
"represent http://localhost" in {
val url = Url(Http, None, None, localhost, None, None, None)
url.toString must beEqualTo("http://localhost")
}
For which I get the following baffling compiler error:
[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)
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
错误在这里:
由于您将
Http
定义为类,而不是对象,因此您需要执行Http()
来创建实例。或者甚至更好:首先将Http
定义为 case 对象。通常首选使用 case 对象而不是不带参数的 case 类。
The error is here:
Since you defined
Http
as a class, not an object, you need to doHttp()
to create an instance. Or even better: defineHttp
as a case object in the first place.It is generally preferred to use case object rather than case classes without arguments.