在可变的hashmap中将项添加到队列中?

时间:2017-10-23 13:01:44

标签: scala

如何将项目添加到Scala中的队列mutable.hashmap

我试过了:

 val hashMapUserListeners: mutable.HashMap[UUID, mutable.Queue[UUID]]
 hashMapUserListeners.get(uuid) += uuid2

但得到了这个错误:

[error]Expression does not convert to assignment because receiver is not assignable.
[error]hashMapUserListeners.get(uuid) += uuid2

实际代码段:

  def listenUserStatus(actorRef: ActorRef, message: SocketParsedMessage)={
      (message.data \ "userId").validate[UUID] match {
        case s: JsSuccess[UUID] => {
          if(hashMapUserListeners.contains(s.get)){
            if(!hashMapUserListeners.get(s.get).contains(hashMapA2U.get(actorRef))) {
              hashMapUserListeners.get(s.get) += hashMapA2U.get(actorRef)
            }
          } else{
            hashMapUserListeners += (s.get -> new mutable.Queue[UUID]())
          }
        }
        case e: JsError => actorRef ! SocketParsedMessage(
          AllowedSocketMessageTypes.LISTEN_USER_STATUS, Json.obj(
            "success" -> false,
            "message" -> "UserId not provided with request"
          ))

2 个答案:

答案 0 :(得分:1)

这不起作用,因为mutable.HashMap.get会返回Option[Queue[UUID]],而不是Queue[UUID]。您需要使用Option使用foreach来更新基础队列:

val maybeUuids: Option[mutable.Queue[UUID]] = hashMapUserListeners.get(uuid)
maybeUuids.foreach(queue => queue += uuid2)

答案 1 :(得分:0)

最后,我将我的代码更改为下面附带的代码。

   hashMapUserListeners.get(s.get) match {
        case Some(currentQueue) => {
               if(!currentQueue.contains(s.get)){
                  currentQueue += userId
               }
        }

对于那些对整个代码感兴趣的人。

 def listenUserStatus(actorRef: ActorRef, message: SocketParsedMessage): Unit = {
    hashMapA2U.get(actorRef) match {
      case Some(user) => {
        (message.data \ "userId").validate[UUID] match {
          case s: JsSuccess[UUID] => {
            hashMapUserListeners.get(s.get) match {
              case Some(x) => {
        case Some(currentQueue) => {
               if(!currentQueue.contains(s.get)){
                  currentQueue += userId
               }
              }
              case None => hashMapUserListeners += (s.get -> new mutable.Queue[UUID]())
            }
          }
          case e: JsError => actorRef ! SocketParsedMessage(
            AllowedSocketMessageTypes.LISTEN_USER_STATUS, Json.obj(
              "success" -> false,
              "message" -> "UserId not provided with request"
            ))
        }
      }
      case None => {
        actorRef ! SocketParsedMessage(
          AllowedSocketMessageTypes.AUTHENTICATE, Json.obj(
            "success" -> false,
            "message" -> "User not authenticated"
          ))
      }
    }
  }