[英]Scala error when defining class
我正在学习Coursera的Scala课程,并且已经实施了follwong课程:
class Rational(x: Int, y: Int) {
def numer = x;
def denom = y;
def add(that: Rational) =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom)
override def toString = numer + "/" + denom;
def main(args: Array[String]){
val x = new Rational(1, 2);
x.numer;
x.denom;
}
}
但是,我遇到许多编译错误。 其中的第一个出现在第一行:
Multiple markers at this line:
self constructor arguments cannot reference unconstructed this
constructor Rational#97120 is defined twice conflicting symbols both originated in file '/Users/octavian/workspace/lecture2/src/ex3.sc'
x is already defined as value x#97118
y is already defined as value y#97119
包含代码的文件称为
Rational.scala
为什么会出现此错误?
您的main
方法必须存在于伴随object
class Rational(x: Int, y: Int) {
def numer = x;
def denom = y;
def add(that: Rational) =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom)
override def toString = numer + "/" + denom;
}
object Rational {
def main(args: Array[String]) : Unit = {
val x = new Rational(1, 2);
x.numer;
x.denom;
}
}
我还更改了主方法签名,因为它可以防止错误来指定显式的返回类型并使用“ =”。 根据经验: 切勿忽略“ =”符号 。
def main(args: Array[String]) : Unit = {
代替
def main(args: Array[String]) {
我在eclipse scala-ide工作表(.sc文件)中定义一个类,并给它一个相同的类名(偶然)时,遇到了错误消息, self constructor arguments cannot reference unconstructed this
的该类,因为我命名了一个类工作表之外的定义。 删除重复的类名,让错误消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.