【发布时间】:2011-05-02 22:49:27
【问题描述】:
下面的代码生成:
名称的 hashCode
名称的 hashCode
名称等于
ID=0
import scala.collection.mutable
object TestTraits {
def main(args: Array[String]): Unit = {
val toto0 = new Person(0,"toto")
val toto1 = new Person(1,"toto")
val peoples = mutable.Set.empty[PersonID]
peoples.add(toto0)
peoples.add(toto1)
peoples.foreach(_.showID)
//peoples.foreach(_.saySomething)//won't compile'
}
}
trait Name{
var theName=""
override def hashCode(): Int = {
println("Name's hashCode")
var hash = 5;
hash = 71 * hash + this.theName.##;
hash
//super.hashCode()//infinite loop
}
override def equals(that: Any): Boolean = {
println("Name's equals")
that match {
case that: Name => this.theName.equals(that.theName)
case _ => false
}
}
}
abstract class PersonID{
val idNumber: Int
override def hashCode(): Int = {
println("PersonID's hashCode")
super.##
}
override def equals(that: Any): Boolean = {
println("PersonID's equals")
that match {
case that: PersonID => this.eq(that)
case _ => false
}
}
def showID: Unit = {
println("ID=" + idNumber)
}
}
class Person(val id:Int, val s:String) extends {
val idNumber=id
} with PersonID with Name {
/*override def hashCode(): Int = {
println("Person's hashCode")
super.## //infinite loop !!
}
override def equals(that: Any): Boolean = {
println("Person's equals")
that match {
case that: Person => this.eq(that)
case _ => false
}
}*/
theName=s
def saySomething: Unit = {
print("Hello, my name is " + theName + ", ")
showID
}
}
由于“peoples”是一组 PersonID,我期待以下输出:
PersonID 的 hashCode
PersonID 的 hashCode
ID=0
ID=1
是否有人可以解释这种行为以及如何做我所期望的(也就是说,除了将实例放在 Set[PersonID] 中时,基于字段值有一个“等于”的类)
另一个谜团是为什么我在自定义 hashCode 中使用 super.hashCode() 时会出现无限循环?
PS:我使用预初始化的抽象成员,因为我在实际用例中需要它......
【问题讨论】:
标签: scala collections multiple-inheritance