2

Please show me how to rewrite toString in a functional way.

The code is ok, but nothing to be proud of, there are 3 temporary variables in it.

class Field(x: Int, y: Int) {
  val value = init(x,y)
  private def init(x: Int, y: Int) = List.fill(x,y)(new Cell)
  override def toString(): String = {
    val temp = new StringBuilder
    for(i <- value) {
      for(j <- i) {
        temp.append(j.toString())
      }
      temp.append("\n")
    }
    temp.mkString
  }
}

Thanks guys!

1 Answer 1

5

What about this (look ma! one line):

override def toString() = value.map(_.mkString).mkString("\n")

Sometimes it frightens me how compact Scala code can be...


BTW if you don't need to reuse init() method you can simply say:

val value = List.fill(x,y)(new Cell)
Sign up to request clarification or add additional context in comments.

5 Comments

Just what I was about to post. Might not be as fast as the original, but it's way shorter and clearer.
Tomasz, yes, I used exactly your one-liner, but I could not rewrite it to handle the fact that the value that I need to concatenate is retrieved by calling the Cell.toString()
@NyitraiLőrinc: List.mkString implicitly calls toString of each element, can you show more code as it works fine for me with custom Cell class
omg, it works. now I will spend a few hours to understand exactly why. thanks :)
I was mislead by writing the Cell.toString after I tossed away the original one liner. I'm new to Scala (and probably to development), but this elegance is simply brilliant. Thx again.

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.