I see a problem with some Scala 2.7.7 code I'm working on, this should not happen if the equivalent was written in Java. Wrong, the code goes, creates a bunch of card players and assigns them to the tables.
class Player(val playerNumber : Int)
class Table (val tableNumber : Int) {
var players : List[Player] = List()
def registerPlayer(player : Player) {
println("Registering player " + player.playerNumber + " on table " + tableNumber)
players = player :: players
}
}
object PlayerRegistrar {
def assignPlayersToTables(playSamplesToExecute : Int, playersPerTable:Int) = {
val numTables = playSamplesToExecute / playersPerTable
val tables = (1 to numTables).map(new Table(_))
assert(tables.size == numTables)
(0 until playSamplesToExecute).foreach {playSample =>
val tableNumber : Int = playSample % numTables
tables(tableNumber).registerPlayer(new Player(playSample))
}
tables
}
}
PlayerRegistrar assigns multiple players between tables. First, it determines how many tables you need to split the players between them and create a list of them.
Then, in the second part of the code, a table is issued to which the player should be assigned, pulls this table from the list and registers a new player in this table.
The list of players in the table is var and is overwritten each time registerPlayer () is called. I checked that this works correctly with a simple TestNG test:
@Test def testRegisterPlayer_multiplePlayers() {
val table = new Table(1)
(1 to 10).foreach { playerNumber =>
val player = new Player(playerNumber)
table.registerPlayer(player)
assert(table.players.contains(player))
assert(table.players.length == playerNumber)
}
}
Then I check the purpose of the table:
@Test def testAssignPlayerToTables_1table() = {
val tables = PlayerRegistrar.assignPlayersToTables(10, 10)
assertEquals(tables.length, 1)
assertEquals(tables(0).players.length, 10)
}
": < 10 > , : < 0 > ". , , registerPlayer() . .