Ravindu De Silva
Ravindu De Silva

Reputation: 29

Scala object oriented programming

In object oriented programming, Objects have their own state and behaviours. The Objects state is stored within instance variables and we use can use objectname to reference them.

instance.variablename notation is used to reference fields and instance methods are invoked by objectname.instancemethodname(parm..).

However in here Scala there are other notations.

As an example: in Scala List I have come across the following notation:

l filter p

In here, l is the name of list instance and p is argument.

This scenario will return a list of elements that satisfy the predicate p.

So my question is what is that notaion and what does it mean?

Upvotes: 0

Views: 215

Answers (1)

Chris K
Chris K

Reputation: 11927

The Scala compiler rewrites l filter p to l.filter(p), they are therefore treated the same at runtime however they look different to the reader and are thus a choice of programming style that affects the readability of the code.

Scala calls this style of invocation 'infix notation' and it is intended to support methods as operations such as + and *. In Java, operators such as + are provided by the JVM, however in Scala they may be defined on a class and then called using the same syntax as though the operator was defined by the JVM in Java.

For example:

case class Foo( v:String ) {
    def +(o:Foo) = Foo(v + o.v)
}

Foo("a").+(Foo("b")) // equals Foo("ab")
Foo("a") + Foo("b") // equals Foo("ab")

Upvotes: 2

Related Questions