我正在关注Coursera的Scala课程,我已经实施了以下课程:
classdef Mesh
properties
nodes; % its object will contain an object array of Node
elements; % its object will contain an object array of Element
end
methods
% Not interesting for this example
end
end
但是,我收到很多编译错误。 第一行出现在第一行:
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
为什么会出现此错误?
答案 0 :(得分:1)
您的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]) {
答案 1 :(得分:0)
我在eclipse scala-ide工作表(.sc文件)中定义一个类时遇到错误消息self constructor arguments cannot reference unconstructed this
,并给它提供相同的类名(偶然),因为我命名为工作表外的类定义。删除重复的班级名称会让错误消失。