【问题标题】:Traits for modifying interfaces in scala在 scala 中修改接口的特征
【发布时间】: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实现吗?
  • 书没有给出正确的解释。

标签: scala hash


【解决方案1】:

你在上面一行回答了你的“Q1”:“问题是 Book 的 hashCode 方法覆盖了 HashCaching 的。”你混入HashCashing,然后覆盖实现,所以它最终永远不会被使用。

在另一个示例中,实现由BaseBook 提供,然后由HashCaching 覆盖,它对其进行扩充,然后由Book 继承。在这种情况下,Book 不会覆盖实现,因此它按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    相关资源
    最近更新 更多