0

In Scala, how to create a class field compiled to public non-final field (from bytecode perspective).

Similar to this (in Java):

public class Meh {
  public String field;
}
Tvaroh
  • 6,645
  • 4
  • 51
  • 55
  • That's not possible in Scala AFAIK. Once you declare a `var` without restricting it to being private or private package, you get getters and setters, not a direct field access. – Yuval Itzchakov Jul 10 '16 at 07:14

1 Answers1

1
  1. It's impossible in 'clean correct way'.

  2. If you really want:

    • define variable as private[this]
    • call via java reflection setAccessible(true) for this field in constructor of companion object.
  3. I don't know details behind your question, but I guess then in most cases adding some java to project will work better ;)

rssh
  • 464
  • 4
  • 5
  • 1
    If the mangled field name doesn't matter, inline accessor forces it: `class C { private[this] var s: String = _ ; @inline private final def s(): String = this.s }` http://stackoverflow.com/q/12486992/1296806 – som-snytt Jul 10 '16 at 14:09