stringscalascala-2.12

Problem rewriting scala method post upgrade to scala 2.12 (from 2.11)


I have the following small but complex method in my project:

private def indent ( s : String )
  = s.lines.toStream match {
    case h +: t =>
      ( ("- " + h) +: t.map{"| " + _} ) mkString "\n"
    case _ => "- "
  }

After upgrading my project from Scala 2.11 to 2.12, it would no longer compile. Error:

CaseClassString.scala:14: value toStream is not a member of java.util.stream.Stream[String]

I tried rewriting like this:

private def indent ( s : String )
  = Stream(s.lines) match {
    case h +: t =>
      ( ("- " + h) +: t.map{"| " + _} ) mkString "\n"
    case _ => "- "
  }

But it is not working.

This method was found in the following project: https://github.com/nikita-volkov/sext

The function would transform a string like:

metricResult: column: value: city
function: density
value: metricValue: 0.1

to:

- metricResult: column: value: city
| - function: density
| - value: metricValue: 0.1

Anyone have other ideas about how to rewrite this method for Scala 2.12?


Solution

  • It seems like that you not only upgraded Scala but also upgraded Java version. The error is simple to understand if you simply look at changes related to String for both Java and Scala.

    import scala.collection.immutable.StringOps
    
    def indent(s : String): String =
      (s: StringOps).lines.toStream match {
        case h +: t =>
          ( ("- " + h) +: t.map{"| " + _} ) mkString "\n"
        case _ => "- "
      }
    
    

    Or, if you are working with Java 11 and don't really need Stream then,

    def indent(s : String): String =
      s.lines.toArray.toList match {
      case h :: t =>
        val indented = ("- " + h) :: t.map{"| " + _}
        indented.mkString("\n")
      case _ => "- "
    }