Scala: Can I declare a public field that will not generate getters and setters when compiled?

后端 未结 2 786
陌清茗
陌清茗 2020-12-10 03:59

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.

E.g.

2条回答
  •  借酒劲吻你
    2020-12-10 04:20

    Presumably you want to force the way your attribute is represented because you're accessing from Java. (If you're trying to "optimise" your byte code by getting rid of the getter then you're wasting your time, the VM will quickly inline them.) Unfortunately for you, to keep the door as wide open as possible for future improvements, the Scala specs don't specify how Scala code should be translated to byte code. This means that even if you find a trick that works for a given version of Scala, it's not guaranteed to work in subsequent versions.

    The recommended approach in these cases is to write the Java-visible code in Java and then have a small glue class written in Scala - something like the answer given by @Emil is great.

提交回复
热议问题