问题描述
在Scala中,什么原因,你不需要使用新来创建一个新的case类?
In Scala what is the reason that you don't need to use "new" to create a new "case class"?I tried searching for awhile now without answers.
推荐答案
你想要如何或为什么?正如其他答案所指出的,如何只是应用
方法对自动生成的随播对象。
Do you want the how or the why? As the other answer notes, the how is just the apply
method on the automatically generated companion object.
对于为什么:case类常常用于实现在Scala中,并且 new
-less构造函数允许更优雅的代码(创建一个值看起来更像通过模式匹配解构它),并且更接近于ADT其他语言的语法。
For the why: case classes are often used to implement algebraic data types in Scala, and the new
-less constructor allows code that is more elegant (creating a value looks more like deconstructing it via pattern matching, for example) and that more closely resembles ADT syntax in other languages.
这篇关于为什么“案例类”不需要“新的”创建一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!