[英]Overriding equals method in Scala
I have the following code. 我有以下代码。 When compiling I get an error saying 编译时我得到一个错误说
value email is not a member of Player
class Player(email: String)
{
override def equals(player: Any): Boolean = {
player match {
case p: Player => email.equals(p.email)
case _ => false
}
}
}
I am a Java programmer trying out Scala and can't figure out why this error is occuring (From what I understand email is a member of player instance). 我是一名尝试Scala的Java程序员,无法弄清楚为什么会出现这个错误(据我所知,email是播放器实例的成员)。 Can someone give an explanation and how to solve this problem? 有人可以给出解释以及如何解决这个问题吗?
email
is only a constructor parameter and not a member of the class itself. email
只是一个构造函数参数,而不是类本身的成员。 You can make it as such by preceding it with val
你可以通过在val
之前加上它来实现它
class Player(val email: String) {
override def equals(player: Any): Boolean = {
player match {
case p: Player => email.equals(p.email)
case _ => false
}
}
}
For completeness, you could also manually make email
a member of Player
: 为完整起见,您还可以手动将email
作为Player
的成员:
class Player(e: String) {
val email: String = e
...
}
Or a def (if you for some reason want to): 或者def(如果你出于某种原因想要):
class Player(e: String) {
def email: String = e
...
}
As mentioned by @srgfed01, you can include access modifiers in the constructor as well. 正如@ srgfed01所提到的,您也可以在构造函数中包含访问修饰符。 For instance: 例如:
class Player(private val email: String)
A case class will generate getters for your class automatically, though they are all public by default. 案例类会自动为您的类生成getter,但默认情况下它们都是公共的。
I prefer the first method for declaring a constructor parameter a class member, as it's clear, concise, and reduces code clutter (imagine if you had 10 params you wanted accessors for). 我更喜欢第一种方法来将构造函数参数声明为一个类成员,因为它清晰,简洁,并且减少了代码混乱(想象一下,如果你有10个params,你想要访问器)。
Instead of using a normal class and writing your own equals method, use a case class, like this: 使用case类,而不是使用普通类并编写自己的equals方法,如下所示:
case class Player(email: String)
The equals and hashCode methods are generated automatically for you. 将自动为您生成equals和hashCode方法。 The extra benefit is that if you change the fields, equals/hashCode are guaranteed to be kept in sync. 额外的好处是,如果您更改字段,则保证equals / hashCode保持同步。 If you're going to do any kind of serialization, most libraries expect case classes anyway. 如果您要进行任何类型的序列化,大多数库都会使用案例类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.