[英]Scala - what is case class private
I am analyzing my existing project, I found some this like this(conceptually): 我正在分析我现有的项目,我发现了一些这样的(概念上):
case class AA private(id: String) {}
case class BB(id: String) {}
After I created those two classes to observe the difference. 在我创建了这两个类来观察差异之后。 I analysed their java source by using java decompiler. 我使用java反编译器分析了他们的java源代码。 I did not find any different. 我没有发现任何不同。
What is the need of private there. 在那里私人的需要是什么。
What is the importance of that. 这有什么重要性。
A case class is a class which gets a Companion object automatically defined with a few helper functions. 案例类是一个类,它使用一些辅助函数自动定义Companion对象。 One of these is an apply method which essentially allows to skip out the 'new' keyword when defining a class. 其中一个是apply方法,它基本上允许在定义类时跳过'new'关键字。 The private keyword in your example makes the constuction of a new AA using the 'new' keyword private. 您的示例中的private关键字使用'new'关键字private来构建新的AA。 Eg: 例如:
case class A private(id: Int)
case class B(id: Int)
A(1) //Using public method
B(1) //Using public method
new A(1) // Using PRIVATE method
new B(1) // Using public method
You can understand this better using Scala REPL 您可以使用Scala REPL更好地理解这一点
scala> case class A private(a: String)
defined class A
scala> new A("")
<console>:14: error: constructor A in class A cannot be accessed in object $iw
new A("")
^
scala> A("")
res3: A = A()
Notice that instantiation of the A
cannot be done using new
keyword. 请注意,使用new
关键字无法实现A
实例化。 private
helps restrict the instantiation of A using new
(makes it private) private
帮助限制使用new
实例化A(使其成为私有)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.