How do I split a String and keep the delimiters?

I keep getting "type mismatch" when trying to use a Seq[Seq[String]] in Scala. Why?

  • Here's my code. class Board (rows: String*) { var cells: Seq[Seq[String]] = rows.map(_.split("")) override def toString() = { for (rows <- cells) for (row <- rows) Console.println(row) } } I don't understand why I get this error: error: type mismatch;  found   : Unit  required: java.lang.String     for (rows <- cells) Why is "cells" now a Unit? And why does it require a String for a for loop?

  • Answer:

    I figured it out, by the way. The problem is that by default, the "for" loop returns type Unit. If you want it to return an array, then you have to use yield. Also, I found that for was a bad choice for a toString method anyway. My new code is this:   override def toString: String =     "[[" + cells.map(_.mkString(", ")).mkString("]\n [") + "]]\n"

Luke Shepard at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.