Operators – Playing With Scala

Posted: August 30, 2009 in Scala

I started learning Scala about 2 months back.I mean I wanted to start but somehow got delayed because of other things.Now again resumed the endeavour and I have got the book “Programming In Scala”.It’s a nice book for the learners and I am finding it really helpful.In this post I am to write a bit about operators in Scala as I found this stuff really very interesting.

Type the following in Scala console

scala> 1 + 2

The output result is very obvious.This is just a simple addition operation.
res0: Int = 3

But if I type

scala> (1).+(2)

I will get the following output:

res0: Int = 3

So what’s happening ?.Every operator in Scala is a method.Here “+” is an infix operator i.e. placed between the two so we are invoking it as a method of  “1” with “2” passed as the parameter.

Similarly the prefix operators also are methods but we need to invoke them a bit differently as shown below.This is equivalent to -1.

scala> (1).unary_-
res18: Int = -1

Similarly we can invoke the methods on an Int as operator

scala> 1 toString
res19: java.lang.String = 1

Let’s see what interesting stuff I encounter next.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.