【问题标题】:SynchronizedSet and set operations in ScalaScala 中的 SynchronizedSet 和 set 操作
【发布时间】:2011-12-12 13:53:05
【问题描述】:

在 REPL 中:

import collection.mutable.{ HashSet, SynchronizedSet }

var myPool = new HashSet[String] with SynchronizedSet[String]
myPool += "oh"
myPool += "yes"
myPool = myPool.tail

我得到:

error: type mismatch;
 found   : scala.collection.mutable.HashSet[String]
 required: scala.collection.mutable.HashSet[String] with scala.collection.mutable.SynchronizedSet[String]
   myPool = myPool.tail
                   ^

我做错了什么?

【问题讨论】:

  • 请注意tail 不会同步。这将是一个新的集合,实例化时没有 SynchronizedSet 特征。

标签: scala set hashset synchronized


【解决方案1】:

正如消息所说,myPool.tail 的类型为 HashSet[String],而您的变量 MyPool 被声明为 HashSet[String] with SynchronizedSet[String]

你只需要声明你想要避免过于精确推断的类型。

var myPool : HashSet[String] = new HashSet[String] with SynchronizedSet[String]

请注意,在可变集合上,tail 是一项代价高昂的操作,会返回一个新集合。那可能不是你想要的。 (此外,规范对于删除哪个元素是沉默的)

【讨论】:

    猜你喜欢
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2011-10-26
    • 2015-03-23
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多