1

I have an assignment where I need to develop N in a row in Scala. For the representation of the board I want to loop through the 2d Array and print the X' en O's. This is the code for that:

  override def toString(): String = {
    val repres = ""

    for (rowIndex <- 0 until board.length - 1) {
      for (columnIndex <- 0 until board(rowIndex).length - 1) {
        if (board(rowIndex)(columnIndex) == Player.Player1) {
          repres + "X"
        } else if (board(rowIndex)(columnIndex) == Player.Player2) {
          repres + "O"
        } else if (board(rowIndex)(columnIndex) == Player.NoPlayer) {
          repres + "_"
        } else {
          throw new IllegalArgumentException
        }
      }
      repres + Properties.lineSeparator
    }
    repres
  }

This is the board:

var board = Array.fill[Player](rows,columns) {Player.NoPlayer}

For some reason it is not going through the for loop even though board.length is 6 in debugging.

I am new to scala so there is probably something very obvious wrong that I am just not seeing.

Thanks for the help

2 Answers 2

3

I think the problem is not the loop. Are you expecting repres to change?

You have declared repres as an immutable String. All the operations you are doing are pretty much futile, it is creating a new String in each branch but you are not assigning it to anything. The last statement returns repres as an empty String.

Try to change the declaration to var repres.

Then each of the branches needs to change to repres = repres + "X" etc.

Note that this is not really functional. It's just Java adapted to Scala syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh thank you. Ofcourse. Completely forgot about that. I was doing repres = repres + "X" before but it gave an error. Didn't realize that was because I was using a val instead of var. I know it is not functional. Point of the assignment is to first do it this way and changing it to functional later
2

You should not be using mutable variables. They make code less readable, and harder to reason about, and may create many hard to debug problems potentially.

In 95% uses cases in scala, you don't need mutable state, so my recommendation is that you just pretend it does not exist at all until you get enough grasp of the language to be able to definitively distinguish the other 5% of the cases.

 val repres = board.flatten.map { 
   case Player.Player1 => "X"
   case Player.Player2 => "O"
   case _ => "_"
 }.mkString
  .grouped(board.length)
  .mkString(Properties.lineSeparator)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.