scala semicolon inference example

2019-07-30 15:02发布

问题:

The "Programming in scala" introduces the rules of semicolon inference:

In short, a line ending is treated as a semicolon unless one of the following conditions is true:

  1. The line in question ends in a word that would not be legal as the end of a statement, such as a period or an infix operator.
  2. The next line begins with a word that cannot start a statement.
  3. The line ends while inside parentheses(...) or brackets[...], because these cannot contain multiple statements anyway.

But I can't find an example that in the second condition,who can give an example? I have tried the following code because * cannot start a statement,but it failed!

    1 * 2
    *3

回答1:

The "Programming in scala" introduces the rules of semicolon inference:

In short, a line ending is treated as a semicolon unless one of the following conditions is true:

  1. The line in question ends in a word that would not be legal as the end of a statement, such as a period or an infix operator.
  2. The next line begins with a word that cannot start a statement.
  3. The line ends while inside parentheses(...) or brackets[...], because these cannot contain multiple statements anyway.

Note that this is a rather simplified view. The full rules are in section 1.2 Newline Characters of the Scala Language Specification.

But I can't find an example that in the second condition,who can give an example?

According to the SLS:

The tokens that can begin a statement are all Scala tokens except the following delimiters and reserved words:

  • catch
  • else
  • extends
  • finally
  • forSome
  • match
  • with
  • yield
  • ,
  • .
  • ;
  • :
  • =
  • =>
  • <-
  • <:
  • <%
  • >:
  • #
  • [
  • )
  • ]
  • }

So, one example could be:

return 42
.toString()

This is equivalent to

return 42.toString(); // returns the `String` "42"

and not

return 42;  // returns the `Int` 42
.toString() // dead code

I have tried the following code because * cannot start a statement,but it failed!

1 * 2
*3

What makes you think that * cannot start a statement? Please, re-read the spec carefully. A method call is perfectly legal starting a statement:

foo(bar)

is valid, and so is

*(3)

Ergo, * can start a statement. Full example:

object Test
  def test = {
    1 * 2
    *(3)
  }

  def *(x: Int) = {
    println(x)
    x + 1
   }
 }

Test.test
// 3
//=> res0: Int = 4


标签: scala