Scala 我需要一个具体的例子来说明如何在一个不可变的_case_类的主构造函数中定义一个局部参数
我有一个普通的Scala类,我想重构成一个不可变的case类。由于我需要该类在Scala 我需要一个具体的例子来说明如何在一个不可变的_case_类的主构造函数中定义一个局部参数,scala,parameters,constructor,case-class,Scala,Parameters,Constructor,Case Class,我有一个普通的Scala类,我想重构成一个不可变的case类。由于我需要该类在Set操作中表现良好,因此我希望在一个case类上提供所有Scala编译器自动生成的方法。我想避免写这些不同的方法等于、hashCode、toString等,因为这很容易出错。我需要对大量的类执行此操作,所以我需要一个通用的解决方案,而不仅仅是一个特定的解决方案—快速修复或破解 以下是我正在工作的班级: class Node(val identity: String, childrenArg: List[Node],
Set
操作中表现良好,因此我希望在一个case类上提供所有Scala编译器自动生成的方法。我想避免写这些不同的方法等于、hashCode、toString等,因为这很容易出错。我需要对大量的类执行此操作,所以我需要一个通用的解决方案,而不仅仅是一个特定的解决方案—快速修复或破解
以下是我正在工作的班级:
class Node(val identity: String, childrenArg: List[Node], customNodeArg: CustomNode) {
val children: List[Node] = childrenArg
val customNode: CustomNode = customNodeArg
}
如您所见,该类的构造函数有三个参数。第一个属性是只读属性,identity
。剩下的两个,childrenArg
和customNodeArg
,只是一个普通的方法参数;i、 e.它们仅在实例构造期间出现,然后在类构造函数执行完成时从类实例中完全消失(除非另有捕获)
我第一次天真地尝试将其转换为不可变的case类是这样的(仅从第一个参数中删除val
):
但是,这导致了childrenArg
和customNodeArg
参数现在被提升为(只读)属性(而不是将其作为正常方法参数)。这还有一个不希望的结果,就是将它们包含在编译器生成的equals
和hashCode
实现中
如何标记不可变case类的构造函数参数childrenArg
和customNodeArg
,以便identity
是case类的唯一只读属性
关于这方面的任何指导;非常感谢您的解答、网站讨论链接等。案例类参数默认为VAL,但您可以将其设置为VAR
case class Node(identity: String, var childrenArg: List[Node], var customNodeArg: CustomNode)
使它们变为vars会自动为您提供getter和setter第二个参数列表似乎可以做到这一点:
scala> trait CustomNode
defined trait CustomNode
scala> case class Node(identity: String)(childrenArg: List[Node], customNodeArg: CustomNode)
defined class Node
scala> val n = Node("id")(Nil, null)
n: Node = Node(id)
scala> n.identity
res0: String = id
scala> n.getClass.getDeclaredFields.map(_.getName)
res1: Array[String] = Array(identity)
这是专门针对Scala案例类的,而不是一般的Scala类。瞧,这不是其他StackOverflow问题的重复:我不认为这不能解决我的问题,因为childrenArg
和customNodeArg
参数仍然是属性;i、 e.它们包含在编译器生成的equals
和hashCode
函数实现中。虽然它是隐含的(我已经编辑了我的问题,使之明确),但我需要case类是不可变的。任何var
参数的存在都会使case类可变。这正是我所寻求的解决方案的类型!天哪!Scala非常灵活,有时我看不到解决方案。我知道其他的参数列表。我只是从来没有见过或想过这样使用它们。令人惊叹的!我用你的解决方案回答了一个不同的StackOverflow问题,这个问题与在有向图中寻找圈有关。我在答案底部的抽象案例类中使用了它:
scala> trait CustomNode
defined trait CustomNode
scala> case class Node(identity: String)(childrenArg: List[Node], customNodeArg: CustomNode)
defined class Node
scala> val n = Node("id")(Nil, null)
n: Node = Node(id)
scala> n.identity
res0: String = id
scala> n.getClass.getDeclaredFields.map(_.getName)
res1: Array[String] = Array(identity)