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