简体   繁体   中英

Scala, trasform filter/foreach of map into For Comprehension

here my code: (Variables to use. Is it possible to create a For Comprehension also here instead of foreach? In this code i search all username into players and put it into playersToLobby)

      private var players: Seq[GamePlayer] = _
      private var totalVotes: Int = this.numberOfPlayers
      private var playersToLobby: Map[String, Int] = Map.empty

      this.players.groupBy(_.username).foreach {
          case(username, _) => this.playersToLobby = this.playersToLobby + (username -> 0)
      }

Then, in this code, i take inside playerToLobby a player with high votes and reset playerToLobby setting it to map.empty. Then i filter gamePlayer to find all alivePlayer and added the all username of alive players into playersToLobby.

    val playerToEliminate = playersToLobby.maxBy(_._2)._1
    this.playersToLobby = Map.empty

    gamePlayer.filter(p => p.username != playerToEliminate && p.isInstanceOf[AlivePlayer]).
      groupBy(_.username).foreach {
      case (username, _) => this.playersToLobby = this.playersToLobby + (username -> 0)
    }

How can i trasform it into a For Comprehension? I have to trasform this into a for comprehension, please, help me ^^"

  • Some case class for a GamePlayer with username and age.

     case class GamePlayer(username: String, age: Int)
  • Change variables to values (as they are immutable/final).

     val gamePlayers: Seq[GamePlayer] = Seq(GamePlayer("me", 30), GamePlayer("you", 25), GamePlayer("eliminate_me", 19)) val playerToEliminate = GamePlayer("eliminate_me", 19) val lobby = Map.empty
  • Some fake method is checking if the player is alive (replace this with your logic).

     def isAlive(player: GamePlayer): Boolean = player.age > 28
  • The for comprehension. Note that I didn't transform what you had in a for comprehension, I tried to understand why you started from those foreach and groupBy, but without further insight I just assume you are still getting a grasp for what for comprehension is. So, I just made some example of it.

     for { p <- gamePlayers if p.username.= playerToEliminate.username && isAlive(p) } yield lobby + (p.username -> p)

This will basically take players from the gamePlayers sequence, filter them and add them to the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM