我是scala的新手,需要澄清以下涉及类的构造函数的代码片段。
class sample (a: Int, b: Int) { /* define some member functions here */ }我能否将变量a和b隐藏到类sample ?
class sample (val a: Int, val b: Int) { /* define some member functions here */ }在这种情况下, a和b公开访问? 在构造函数的参数列表中添加val关键字的确切作用是什么? 如果我使用def关键字而不是val ,它是否也具有相同的效果?
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?
最满意答案
class sample (a: Int, b: Int)a和b在这种情况下是私人的。 用javap反汇编显示a和b不是类的一部分(Scala调用这些类字段):
public class Sample extends java.lang.Object implements scala.ScalaObject{ public Sample(int, int); }a和b先于val。 使用javap反汇编显示a和b现在是Sample中的公共字段。
class sample (val a: Int, val b: Int)
public class Sample extends java.lang.Object implements scala.ScalaObject{ public int a(); public int b(); public Sample(int, int); }在构造函数中使用def而不是val ,它不会编译。 def用于定义函数。 不知道你是否可以在构造函数中使用def作为参数。
另外请注意,私人和受保护的行为与您所期望的相同。 鉴于这种:
class Sample(private val a: Int, protected val b: Int, val c: Int)使用javap反汇编到以下内容:
public class Sample extends java.lang.Object implements scala.ScalaObject{ public int b(); public int c(); public Sample(int, int, int); } class sample (a: Int, b: Int)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):
public class Sample extends java.lang.Object implements scala.ScalaObject{ public Sample(int, int); }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)
public class Sample extends java.lang.Object implements scala.ScalaObject{ public int a(); public int b(); public Sample(int, int); }With def instead of val in the constructor it won't compile. def is for defining functions. Not sure if you can use def in constructor as a parameter.
Also, note that private and protected behave as you would expect. Given this:
class Sample(private val a: Int, protected val b: Int, val c: Int)Disassembles to the following with javap:
public class Sample extends java.lang.Object implements scala.ScalaObject{ public int b(); public int c(); public Sample(int, int, int); }更多推荐
发布评论