类构造函数声明...声明同一事物的两种方法?
我想解释一下这个声明:
class Clazz(param1: String, param2: Integer)
和这个:
class Clazz(param1: String)(param2: Integer)
第二个声明是否只影响实例化对象的方式,或者是否有任何我不知道的更深层次的原因。
我想到的一个原因是参数的多个可变长度,例如:
class Clazz(param1: String*)(param2: Integer*)
还有其他的吗?
I would like an explanation of difference for example between this declaration:
class Clazz(param1: String, param2: Integer)
and this one:
class Clazz(param1: String)(param2: Integer)
Does second declaration affect just the way of instantiating the objects or is there any deeper reason I don't know about.
One reason I thought about would be multiple variable length of parameters for example:
class Clazz(param1: String*)(param2: Integer*)
So are there any others?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
#1 类型推断。它从左到右并按参数列表完成。
#2 隐式参数列表。
#1 Type inference. It goes from left to right and is done per parameter list.
#2 Implicit parameter list.
在第二个版本中,您为 Clazz 声明一个柯里化主构造函数。因此,这两个版本之间的差异与 Scala 中“普通”函数和柯里化函数之间的差异相同,即
大多数情况下,两个声明可以互换使用,但如果您经常需要柯里化函数,那么在中声明它更有意义咖喱形式。请注意,您还可以将普通函数甚至构造函数转换为柯里化形式,例如,您可以使用以下方法将普通 Clazz 构造函数转换为柯里化形式:
如果您传递隐式值,则还需要多个参数列表(因为关键字隐式适用)到完整的参数列表)
In the second version you are declaring a curried primary constructor for Clazz. So the difference between the two versions is the same as difference between "normal" and curried functions in Scala, i.e.
Most of the time both declarations can be used interchangeably but if you often need to curry function then it makes more sense to declare it in curried form. Note you can also convert a normal function or even constructor into a curried form, for e.g you could transform your normal Clazz constructor into curried form using this:
You also need multiple parameter lists if you are passing an implicit value (as the keyword implicit applies to the complete parameter list)