【发布时间】:2017-01-09 13:07:34
【问题描述】:
谁能解释一下 Martin Odersky 所著的“Scala 编程”一书中有关使用特征修改接口的示例。
trait HashCaching {
private var cachedHash: Int = 0
private var hashComputed: Boolean = false
/** Override the default Java hash computation */
override def hashCode = {
if (!hashComputed) {
cachedHash = super.hashCode
hashComputed = true
}
cachedHash
}
}
但是,尝试使用它会遇到问题:
class Book(val author: String, val title: String) extends Ordered[Book] with HashCaching {
// compare and equals() as before...
override def hashCode = {
Thread.sleep(3000) // simulate a VERY slow hash
author.hashCode + title.hashCode
}
}
此版本未缓存其哈希码!问题是书的 hashCode 方法覆盖了 HashCaching 的。
Q.1 我不明白为什么哈希码没有被缓存?
然后作者继续给出以下解决方案:
abstract class BaseBook(val author: String, val title: String) {
override def hashCode = {
Thread.sleep(3000)
author.hashCode + title.hashCode
}
}
class Book(author: String, title: String) extends BaseBook(author, title) with Ordered[Book] with HashCaching {
// compare and equals() as before...
}
Q.2 如何在基类效果中覆盖哈希码,现在哈希码会被缓存?
我无法理解这个例子中的任何内容,请解释一下。
【问题讨论】:
-
注意当 trait 调用
super函数时调用的是哪个实现。 -
这本书给出了什么样的解释?
-
@Suma Trait 会调用java的hashcode实现吗?
-
书没有给出正确的解释。