0

In most programming languages (like Java or Python) we use the "\" character at the end of a line to indicate that the code on the next line of documentation is a continuation of what should be executed as a single line of code. However, in Scala, if we use the "\" character, and the user, copies and pastes the two or more lines of code into the Scala interactive shell and tries to execute it, it fails.

How should someone writing scala code in a document, where the single command to run will not fit on one line of text, properly document the code and simultaneously support copy/paste?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
dmohr
  • 2,699
  • 1
  • 22
  • 22

2 Answers2

1

Usually, you can write the code to avoid newline inference.

For items which must paste into one REPL line:

scala> trait A ; object A
defined trait A
defined object A

scala> trait A {
     | } ; object A
defined trait A
defined object A

For items which must compile correctly in paste mode:

trait X {
  //def f = 1
  //  * 2
  def f =
    1 * 2
  def g = 1 *
    2
}

For long string literals, use multiline and stripmargin:

  def s = """
    |This is a long
    | string.
    """.stripMargin.lines.mkString.trim

This is a generic problem for people who don't like long lines.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
1

Well, on the other hand the easy solution is to use the paste mode of the scala REPL.

Just type :paste to enter the paste mode and ctrl+D to end it.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235