Monday, September 14, 2009

Syntactic sugar

In the spirit of making Scala scalable from scripts up to systems, Scala contains some syntactic sugar to make scripting and internal DSLs a bit easier to write. For example there are several situations where the '.' and '()' for method calls are optional. Semi-colons are optional (except for single-line statements).

There are some corner cases but the basic rule is that you need an odd number of arguments if you wish leave out the '.'.
Examples:
  1. scala> "hello" substring (1,3)
  2. res0: java.lang.String = el
  3. scala> "hello" substring 1
  4. res1: java.lang.String = ello
  5. scala> 1 toString ()
  6. res2: java.lang.String = 1


Precendence runs left to right so:
  1. "hello" contains "hello world" toString ()

becomes
  1. "hello".contains("hello world").toString()

Another example:
  1. scala> "hello" contains "hello world" toString () substring 4
  2. res6: java.lang.String = e
  3. scala> "hello".contains("hello world").toString().substring(4)
  4. res7: java.lang.String = e


There is some operator precendence which we will cover later. Operator precedence allows statements like the following:
  1. scala> "hello" substring 6 - 4
  2. res8: java.lang.String = llo
  3. scala> "hello" substring  (6 - 4)
  4. res9: java.lang.String = llo
  5. scala> "hello".substring  (6 - 4)
  6. res10: java.lang.String = llo

No comments:

Post a Comment