I’m new to scala and need clarification on the following code snippet involving constructors for classes.
class sample (a: Int, b: Int) {
/* define some member functions here */
}
Can I take that the variables a and b are private to the class sample?
class sample (val a: Int, val b: Int) {
/* define some member functions here */
}
And in this case, are a and b publicly accessible? What is the exact effect of adding the val keyword in the parameter list for the constructor? And if I use the def keyword instead of val, does it have the same effect as well?
a and b are private in this case. Disassembling with javap shows a and b are not part of the class(Scala calls these class fields):
a and b preceded with val. Disassembling with javap shows a and b are now public fields in Sample.
class sample (val a: Int, val b: Int)With
definstead ofvalin the constructor it won’t compile.defis for defining functions. Not sure if you can usedefin constructor as a parameter.Also, note that private and protected behave as you would expect. Given this:
Disassembles to the following with javap: