Scala:我可以声明一个在编译时不会生成 getter 和 setter 的公共字段吗? [英] Scala: Can I declare a public field that will not generate getters and setters when compiled?

查看:26
本文介绍了Scala:我可以声明一个在编译时不会生成 getter 和 setter 的公共字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,当您声明 val 或 var 时,Scala 会在编译为字节码时自动生成一个私有字段以及 getter 和 setter.

In Scala when you declare a val or a var, Scala will automatically generate a private field and the getters and setters for you when compiled to bytecode.

例如

class myClass {
    val name = "My Name"
}

将编译以创建等效项

class myClass {
    private string name;
    public string name();
    public void name_$eq(string);
}

其中 name() 和 name_$eq 是私有字符串名称的 getter 和 setter.

Where name() and name_$eq are the getters and setters for the private string name.

我知道您可以通过将私有字段声明为 private[this] val/var blah 来强制它不为私有字段提供 getter 和 setter,但是我需要能够创建一个不生成 getter 和编译时的 setter.

I know you can force it to not provide the getters and setters for private fields by declaring them as private[this] val/var blah, but I need to be able to create a public field that doesn't generate getters and setters when compiled.

这在 Scala 中是否可行?

Is this even possible in Scala?

谢谢

推荐答案

生成的类不包含 getter 或 setter,如您提供的示例所示. 生成的类不包含 javabean getter 或 setter.要实际让编译器为 var 生成 getXsetX 方法,您需要使用 @BeanProperty 注释该变量.

The generated class does not contain getters or setters as can be seen in the sample you provided. The generated classes does not contain java bean getters or setters. To actually make the compiler generate getX and setX methods for a var you need to annotate that variable with @BeanProperty.

如果您想拥有一个可从 Java 访问的公共字段,我认为您很不幸.至少,我还没有看到仅使用 Scala 来实现这一目标的方法.

If you would like to have a public field accessible from java I think you are out of luck unfortunately. Atleast, I have not seen a way to accomplish that only using scala.

你可以通过混合Scala和Java来完成它.使用 java 类,如:

You could accomplish it by mixing scala and java. With a java class like:

public abstract class JavaClassWithPublicField {
   public String name = "My name";
}

然后在您的 Scala 代码中继承该类:

And then in your scala code inherit that class:

class ScalaClassWithPubilcField extends JavaClassWithPublicField

这可能是最干净的方法.

That's likely the cleanest way to do it.

这篇关于Scala:我可以声明一个在编译时不会生成 getter 和 setter 的公共字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆