一个案例类的备用构造函数

huangapple go评论52阅读模式
英文:

Alternate constructor for a case class

问题

trait mobility {
   def limit : Int
}

final case class Car {
  brand : String,
  manufacture : Int,
  override val limit: Int
} extend mobility

object Car {
  def apply(
    brand : String,
    manufacture : Int,
  ): Car = Car( brand , manufacture , 0)
}

编译错误 : 

> 无法解析重载的方法 "Car"

我在这里做错了什么?
英文:
trait mobility {
   def limit : Int
}

final case class Car {
  brand : String,
  manufacture : Int,
  override val limit: Int
} extend mobility

object Car {
  def apply(
    brand : String,
    manufacture : Int,
  ): Car = Car( brand , manufacture , 0)
}

Compilation error :

> Cannot resolve overloaded method "Car"

What am I doing incorrect here?

答案1

得分: 3

这段代码无法编译。在案例类的定义中存在语法错误。

final case class Car {
                     ^

类的属性应该包含在括号内,而不是花括号。

另一个错误是继承类的保留字应该是 extends 而不是 extend

} extends mobility
  ^^^^^^^

只需修复这些问题,代码就应该可以正常工作。

查看这个 scatsie 示例 ,使用建议的修复来运行您的代码。

英文:

That code will not compile. You have a syntax error in the definition of the case class

final case class Car {
                     ^

The attributes of the class should be wrapped inside a parentheses instead of a curly braces.

Another error you have is that the reserved word to inherit a class is extends not extend

} extend mobility
  ^^^^^^

just fixing that, it should work.

Check this scatsie example using your code with the suggested fix

huangapple
  • 本文由 发表于 2023年7月4日 23:59:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定