Someone once told me that all public fields, by nature of the language were automatically wrapped in getters and setters. And I believed that until I checked the kind in IDEA's intellisense.
So say we have a simple class
class Something {
val a = 5
}
Then writing (new Something). IDEA would show a as being a value.
Conversely however, doing the exact same thing in Eclipse, a would be shown as a def, which puts me on the fence here.
Which one's correct? Is the value wrapped in a function at compile time, and IDEA is simply being confusing? Or is it just a value/variable and I've been mistaken the whole time?
A field and a getter are being generated, however the getter is not prefixed by get as would be the expectation in Java. It is instead given the same name as the field. To confirm this we can dissect the class file that is generated by scalac by using javap.
first compile Something.scala
javap -p Something.class
public class starling.launcher.utils.Something implements scala.ScalaObject {
private final int a;
public int a();
public starling.launcher.utils.Something();
}
and then just for fun, here is the jvm byte codes for a(), which confirms that it is indeed a straight forward getter method for a field.
javap -c Something.class
public int a();
Code:
0: aload_0
1: getfield #11 // Field a:I
4: ireturn
>
If we go on to change val to var, then the code changes to the following. Which includes a setter method, which has the rather 'unusual' name of a_$eq.
public class starling.launcher.utils.Something implements scala.ScalaObject {
private int a;
public int a(); // getter method
public void a_$eq(int); // setter method
public starling.launcher.utils.Something();
}
and to confirm that a_$eq is a setter method, here is its byte code.
public void a_$eq(int);
Code:
0: aload_0
1: iload_1
2: putfield #11 // Field a:I
5: return
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With