Scala getters and setters in Java class -
i create java class follows scala setters/getters convention.
i tried following simple class, not work:
public class javaa { private int = 0; public int a() { return a; } public void a_$eq(int a) { this.a = a; } } but when try access scala:
val x = new javaa x.a = 1 and "reassignment val" error message. tried this, issues found other way around scala java.
what right way it?
thanks!
you can sort of this, , it's hard enough don't want to.
what can't write bare java class magically interpreted scala getters , setters. reason scala embeds information class file requires getters , setters (e.g. there 0 parameter blocks or 1 empty parameter block--a distinction not preserved on jvm (or in java)).
what can use java implement scala-defined interface (i.e. trait):
// getseta.scala trait getseta { def a: int; def a_=(a: int): unit } // javausesgsa.java public class javausesgsa implements getseta { private int = 0; public int a() { return a; } public void a_$eq(int a) { this.a = a; } } what can't do, so, use class directly (again because java not add appropriate annotation information scala):
scala> j.a = 5 <console>:8: error: reassignment val j.a = 5 but since does implement trait successfully, can use desired when typed trait:
scala> (j: getseta).a = 5 (j: getseta).a: int = 5 so it's rather mixed bag. not perfect means, may sufficiently functional out in cases.
(the other alternative, of course, provide implicit conversion java class 1 has getter/setter references real methods on java class; works when can't have java inherit scala.)
(edit: of course there's no critical reason compiler must act way; 1 argue interpreting java-defined getter/setter pairs if scala ones (i.e. if classfile not explicitly it's scala) candidate feature enhancement improve java interoperability.)
Comments
Post a Comment