Scala 如何访问Java对象';s字段名为";“类型”;来自斯卡拉
我已经有一个用Java编写的类(假设这个类叫做Scala 如何访问Java对象';s字段名为";“类型”;来自斯卡拉,scala,interop,Scala,Interop,我已经有一个用Java编写的类(假设这个类叫做X),它包含一个名为type的字段/成员 现在我想编写一个Scala类/对象,创建一个X类型的对象,并访问该对象的type成员 然而,由于在Scala中,type是一个关键字,所以这不起作用。Eclipse中的错误消息是:需要标识符,但找到了“type”。 问题:是否可以访问该字段而不重命名 一个有效的例子: Java类: public class X { public final int type = 0; } Scala应用程序: obj
X
),它包含一个名为type
的字段/成员
现在我想编写一个Scala类/对象,创建一个X
类型的对象,并访问该对象的type
成员
然而,由于在Scala中,type
是一个关键字,所以这不起作用。Eclipse中的错误消息是:需要标识符,但找到了“type”。
问题:是否可以访问该字段而不重命名
一个有效的例子: Java类:
public class X {
public final int type = 0;
}
Scala应用程序:
object Playground extends App {
val x : X = new X();
System.out.println(x.type); // This does not work!
}
您可以使用反勾号将保留字用作名称,例如,
类型
。有关更多信息,请参见前面的问题:
您可以使用反勾号将保留字用作名称,例如,
键入
。有关更多信息,请参见前面的问题:
使用反勾号或定义一个getter
object Playground extends App {
val x : X = new X();
System.out.println(x.`type`)
}
或者使用吸气剂
public class X {
public int type = 0;
public int getType() {
return type;
}
}
object Playground extends App {
val x : X = new X();
System.out.println(x.getType());
}
使用反勾号或定义一个getter
object Playground extends App {
val x : X = new X();
System.out.println(x.`type`)
}
或者使用吸气剂
public class X {
public int type = 0;
public int getType() {
return type;
}
}
object Playground extends App {
val x : X = new X();
System.out.println(x.getType());
}
谢谢由于字段是原始应用程序中的最终字段(只是编辑了问题),我们并不是故意编写getter的,而是个好主意!我也不喜欢Getter,太冗长了
@Getter
对于静态
变量,听起来不是很好。谢谢!由于字段是原始应用程序中的最终字段(只是编辑了问题),我们并不是故意编写getter的,而是个好主意!我也不喜欢Getter,太冗长了<代码>@Getter对于静态
变量,听起来并不是很好。