What are all the instances of syntactic sugar in Scala?
What are all the instances of syntactic sugar in Scala?
They are hard to search for since most/all of them are purely symbols and are thus hard to search for without knowing the name of the concept.
TODO:
- Implicit conversions
-
_
syntax for anonymous functions - Other things I'm forgetting
Solution 1:
Basics:
-
a b
is equivalent toa.b
. -
a b c
is equivalent toa.b(c)
, except whenb
ends in:
. In that case,a b c
is equivalent toc.b(a)
. -
a(b)
is equivalent toa.apply(b)
This is why the following definitions for an anonymous functions are identical:val square1 = (x: Int) => x*x val square2 = new Function1[Int,Int] { def apply(x: Int) = x*x }
When calling
square1(y)
, you are actually callingsquare1.apply(y)
whichsquare1
must have as specified by theFunction1
trait (orFunction2
, etc...) a(b) = c
is equivalent toa.update(b,c)
. Likewise,a(b,c) = d
is equivalent toa.update(b,c,d)
and so on.-
a.b = c
is equivalent toa.b_=(c)
. When you create aval
/var
x
in a Class/Object, Scala creates the methodsx
andx_=
for you. You can define these yourself, but if you definey_=
you must definey
or it will not compile, for example:scala> val b = new Object{ def set_=(a: Int) = println(a) } b: java.lang.Object{def set_=(Int): Unit} = $anon$1@17e4cec scala> b.set = 5 <console>:6: error: value set is not a member of java.lang.Object{def set_=(Int): Unit} b.set = 5 ^ scala> val c = new Object{ def set = 0 ; def set_=(a:Int) = println(a) } c: java.lang.Object{def set: Int; def set_=(Int): Unit} = $anon$1@95a253 scala> c.set = 5 5
-a
corresponds toa.unary_-
. Likewise for+a
,~a
, and!a
.-
a <operator>= b
, where<operator>
is some set of special characters, is equivalent toa = a <operator> b
only ifa
doesn't have the<operator>=
method, for example:class test(val x:Int) { def %%(y: Int) = new test(x*y) } var a = new test(10) a.x // 10 a %%= 5 // Equivalent to a = a %% 5 a.x // 50
Solution 2:
Special Classes: Tuples and Symbols
As mentioned by Rahul G, tuples and symbols get a slightly special syntax.
- Symbols: the syntax
'x
is short forSymbol("x")
- Tuples:
(p1,p2,..,pn)
is short for a case classTuplen[T1,T2,..,Tn](p1,p2,..,pn)
For example, the following two are equivalent.
val tuple1 = ("Hello",1)
val tuple2 = Tuple2[String,Int]("Hello",1)