Thursday 10 November 2011

"Operator Overloading" in Scala

So, I've been teaching myself Scala recently, and it's a very interesting language.

One of the nice things I like about it, is it's support for creating DSLs, domain specific languages. A domain specific language - or at least my understanding of it - is a language that is written specifically for one problem domain. One example would be SQL, great for querying relational databases, useless for creating first person shooters.

Of course Scala itself is not a DSL, it's a general purpose language. However it does offer several features that allow you to simulate a DSL, in particular operator overloading, and implicit conversions. In this post I'm going to focus on the first of these...

Operator Overloading

So what's operator overloading?

Well operators are typically things such as +, -, and !. You know those things you use to do arithmetic on numbers, or occasionally for manipulating Strings. Well, operator overloading - just like method overloading - allows you to redefine their behaviour for a particular type, and give them meaning for your own custom classes.

Hang on a minute! I'm sure someone once told me operator overloading was evil?

Indeed, this is quite a controversial topic. It's considered far too open for abuse by some, and was so maligned in C++ that the creators of Java deliberately disallowed it (excepting "+" for String concatenation).

I'm of a slightly different opinion, used responsibly it can be very useful. For example lots of different objects support a concept of addition, so why not just use an addition operator?

Lets say you were developing a complex number class, and you want to support addition. Wouldn't it be nicer to write...

Complex result = complex1 + complex2;

...rather than...

Complex result = complex1.add(complex2);

The first example is much more natural don't you think?

So Scala allows you to overload operators then?

Well, not really. In fact, technically not at all.

So all this is just a tease? This is the most stupid blog post I've ever read. Scala's rubbish. I'm going back to Algol 68.

Wait a second, I've not finished. You see Scala doesn't support operator overloading, because it doesn't have operators!

Scala doesn't have operators? You've gone mad, I write stuff like "sum = 2 + 3" all the time, and what about all those funny list operations? "::", and ":/". They look like operators to me!

Well they're not. The thing is, Scala has a rather relaxed attitude to what you can name a method.

When you write...

sum = 2 + 3,

...you're actually calling a method called + on a RichInt type with a value of 2. You could even rewrite it as...

sum = 2.+(3)

...if you really really wanted to.

Aha, I got it. So how do you go about overloading an operator then?

Simple, it's exactly the same as writing a normal method. Here's an example.

class Complex(val real : Double, val imag : Double) {
  
  def +(that: Complex) = 
            new Complex(this.real + that.real, this.imag + that.imag)
  
  def -(that: Complex) = 
            new Complex(this.real - that.real, this.imag - that.imag)

  override def toString = real + " + " + imag + "i"
  
}

object Complex {
  def main(args : Array[String]) : Unit = {
       var a = new Complex(4.0,5.0)
       var b = new Complex(2.0,3.0)
       println(a)  // 4.0 + 5.0i
       println(a + b)  // 6.0 + 8.0i
       println(a - b)  // 2.0 + 2.0i
  }
}
Ok that's nice, what if I wanted a "not" operator though, ie something like a "!"

That's a unary prefix operator, and yes scala can support these, although in a more limited fashion than an infix operator like "+"

Only four operators can be supported in this fashion, +, -, !, and ~. You simply need to call your methods unary_! or unary_~, etc. Here's how you might add a "~" to calculate the magnitude of a Complex number to our complex number class

class Complex(val real : Double, val imag : Double) {
    // ...
    def unary_~ = Math.sqrt(real * real + imag * imag)
}

object Complex {
  def main(args : Array[String]) : Unit = {
     var b = new Complex(2.0,3.0)
     prinln(~b) //  3.60555
   }
}

So that's all pretty simple, but please use responsibly. Don't create methods called "+" unless your class really does something that could be interpreted as addition. And never ever redefine the binary shift left operator "<<" as some sort of substitute for println. It's not clever and you'll make the Scala gods angry.

Hope you found that useful. Next up I'll cover implicit conversions. Another nice feature of Scala that really allows you to write your code in a more natural way

89 comments:

Jan said...

Wow! That's quite tough stuff. Only worked with this in the past: http://www.kammerath.co.uk/The-Joys-of-functional-programming-in-Scala.html

Anonymous said...

Operator overloading in C++

ADmin said...

Case in point there are chronicled heroes who are to a uk-essay.net/essays great degree -they're gay -however they're greatly manly.

Arsalan Yousuf said...

Thanks for sharing your good thoughts and idea here.are you struggling with your essays Just continue on sharing your talent and creation to us readers. There are valuable information. Thanks for sharing.

Unknown said...

academic paper writing

Essay writing services said...

I had been from suffering this problem for a long time but at last this code cleared all my problems..Thanks a lot for sharing this code and making it so simple..

Essay writing service

Unknown said...

Ranthambore, as one of the best national parks in the world to see Bengal tigers, wild, in their natural home. Here can see Bengal tigers as well as Sundari, Machali, Star male, Jumru and so on. Each of Ranthambore denizens is well recognized and The Ranthambhore Bagh, with its trained team, is perhaps your best bet to know who is who.
Ranthambore Tiger Reserve
Ranthambore Safari Booking

Unknown said...

That’s really very useful. Alright, thanks for all this information! I learned a couple of things.
order assignment

aliyaa said...

If you are going to write cover letter for a job application so keep in mind judt one thing that your written statement will be direct approach if it is written well.

Curtis said...

I also do like Scala as it provides a better and more natural support for functional and monadic constructs. Law School Admission Essay Proofreaders. I see we have a lot in common in preferences. Thanks for sharing. Purchase Essays Writer Service

expertshelp said...

Its quite a nice blog, it has very interesting and engaging content that would be great to read again. Such a post is well written, SMO professionals is another page to refer to for reliable information.

Unknown said...
This comment has been removed by the author.
Unknown said...

Tom has a good programming blog and I have learned a lot about operator overloading in scala. I have found scala programming language to be more interesting than I imagined. I have been using c++, c, Java, and, R programming languages. I am developing a computer program that will Help Write a Physics Lab Report and from what you have explained in this blog, scala will the perfect programming language to use.

writing tips said...

Very nice posting ,i hope every one who has wish to read this blog will like this posting and will share it with his friends and families.i am happy to know that you are as hard working as Dissertation Writers UK
Coursework writing services

Unknown said...

thanks

Anonymous said...

Tom has a good programming blog and I have learned a lot about operator overloading in scala. I have found scala programming language to be more interesting than I imagined. I have been using c++, c, Java, and, R programming languages. http://watchtvdrama.com/
http://watchtvdrama.com/bigg-boss-12/
http://www.unikaas.com
https://unikaas.com/replica-clothing-supplier/
http://bikeparts.pk
http://desiseries.com
http://desiseries.com/bigg-boss-12
http://dramavideo.co/
http://dramavideo.co/colors-tv/bigg-boss-12/

Anonymous said...



Its quite a nice blog, it has very interesting and engaging content that would be great to read again. Such a post is well written, SMO professionals is another page to refer to for reliable information. https://cosmocarparts.com/brand/toyota/vitz/
https://cosmocarparts.com/brand/toyota/prado/
https://cosmocarparts.com/brand/toyota/corolla
https://cosmocarparts.com/brand/toyota/land-cruiser
https://cosmocarparts.com/brand/toyota/prius
https://cosmocarparts.com/brand/toyota/aqua

priya rajesh said...

This is very interesting you are a skilled blogger.
Python Training in Chennai
Python classes in Chennai
ccna course in Chennai
AWS Training in Chennai
DevOps Training in Chennai
Angularjs Training in Chennai
RPA Training in Chennai
UiPath Training in Chennai
Blue Prism Training in Chennai

Sai Elakiyaa said...


I have read your article throughly and it was awesome content with great example.

Hadoop Training in Chennai
Android Training in Chennai
Selenium Training in Chennai
Digital Marketing Course in Chennai
JAVA Training in Chennai
German Classes in chennai
German Courses in chennai

Angel Claudia said...

We are the best online Online Essay Editing Service around, and you will not have to worry about submitting an assignment that has been written in the wrong context.

Angel Claudia said...

Our Pay for Essay online services makes your school life bearable and fulfilling by enabling you to pass your exams and also in other research and essay writing tasks.

Unknown said...

7 tips to start a career in digital marketing

“Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”

we have offered to the advanced syllabus course digital marketing for available join now

more details click the link now

[url]https://www.webdschool.com/digital-marketing-course-in-chennai.html [/url]

Unknown said...

Web designing trends in 2020

When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

we have offered to the advanced syllabus course web design and development for available join now

more details click the link now

[url]https://www.webdschool.com/web-development-course-in-chennai.html[/url]

Bhanu sri said...

nice information.
healthcare analytics
'https://360digitmg.com/india/life-sciences-and--certification-programmer
360DigiTMG has developed the Certification Program in Healthcare Analytics. This course is meticulously designed to suit both Healthcare practitioners, IT Business Analysts and Data Scientists.

dataexpert said...

Very nice job... Thanks for sharing this amazing and educative blog post! ExcelR Pune Digital Marketing Course

subha said...

Nice tutorial. I like your post. Thanks for sharing. share more details.
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

priyasri said...

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
360digitmg business analytics courses

sudhan said...

It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
Cyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course

Tech Institute said...

Fantastic blog with excellent information, enjoyed reading it and content was very helpful thanks for sharing.
typeerror nonetype object is not subscriptable

Pro Dissertation Writing said...

+Paper Lords is one of the leading academic paper uk provider agencies in the United Kingdom.
We have been offering our services in the market for over 5 triumphant years.

EXCELR said...

Great Article. Thank you for sharing! Really an awesome post data science course in Hyderabad

OGEN Infosystem (P) Limited said...

Really amazing information, thanks for sharing this valuable information with us. Visit Ogen Infosystem for the best website designing services and PPC Services at an affordable price.
Web Designing Company

Pathway for German Language said...
This comment has been removed by the author.
rajmohan1140 said...

Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us.


Java Training in Chennai

Java Course in Chennai

360DigiTMGAurangabad said...

Your content is very unique and understandable useful for the readers keep update more article like this.
business analytics course in aurangabad

Lauren Rose said...

Paper Lords is offering Assignment Writing across the United Kingdom. We have a team of some quality experts and professional editors that ensure the quality by fulfilling all the requirements of students with a qualitative workforce.

Lauren Rose said...

Paper Lords is offering Assignment Writing across the United Kingdom. We have a team of some quality experts and professional editors that ensure the quality by fulfilling all the requirements of students with a qualitative workforce.

Lauren Rose said...

Paper Lords is offering Assignment Writing across the United Kingdom. We have a team of some quality experts and professional editors that ensure the quality by fulfilling all the requirements of students with a qualitative workforce.

Lauren Rose said...

Paper Lords is one of the leading Academic Writing Services provider agency in the United Kingdom.
We have been offering our services in the market for over 5 triumphant years.

Lauren Rose said...

Paper Lords is one of the leading Academic Writing Services provider agency in the United Kingdom.
We have been offering our services in the market for over 5 triumphant years.

Lauren Rose said...

Paper Lords is one of the leading Academic Writing Services provider agency in the United Kingdom.
We have been offering our services in the market for over 5 triumphant years.

Lauren Rose said...

Paper Lords is one of the leading Academic Writing Services provider agency in the United Kingdom.
We have been offering our services in the market for over 5 triumphant years.

Lauren Rose said...

Paper Lords is one of the leading Academic Writing Services provider agency in the United Kingdom.
We have been offering our services in the market for over 5 triumphant years.

data scientist course said...

Amazing journal. I appreciated studying your articles. this can be extremely a fantastic perused on behalf of me. I even have bookmarked it and that i am anticipating studying new articles. Keep doing awesome!
data scientist course

Huongkv said...

Đặt vé máy bay tại đại lý Aivivu, tham khảo

săn vé máy bay giá rẻ đi Mỹ

giá vé máy bay từ mỹ về việt nam tháng 12

vé máy bay hà nội nha trang vietjet

vé máy bay hcm đi phú quốc

vé máy bay đi huế giá rẻ

dataanalyticscourse said...

good information seeking more such blogs in future.
machine learning course

360digiTMG Training said...

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
business analytics course


Fox Chamber said...

Fox Chamber is the Best SEO Services Agency that will assist your website to achieve a higher ranking. We offer the foremost SEO services to our clients.


skiphirenear.uk said...

Skip Hire Leeds offers the best price skip hire in Leeds Guaranteed. Our Price Promise ensures that we beat any like for like skip hire quote. Compare Prices Now!

Fox Chamber said...

Fox Chamber is the Top digital marketing service that provides complete business solutions and the Best Advertising Agency

Unknown said...

I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
starpmo.com/pmp-certification-training-in-hyderabad Pmp training

traininginstitute said...

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoy every little bit of it and I have you bookmarked to check out new stuff you post.
business analytics course

Activatecard said...


Thank you for posting such a great information ……. myhtspace


Thank you for posting such a great information ……. card activation

Jacob Weber said...

Best MCA Leads is your long-run strategic growth partner with expertise within the Merchant Cash Advance Leads and various business loans. We have a tendency to focus on targeted campaigns and end-to-end lead generation services bound to bring best, exceptional results for our shoppers

Business Leads World said...

Best Qualified Leads For MCA is your long-run strategic growth partner with expertise within the Merchant Cash Advance Leads and various business loans. We have a tendency to focus on targeted campaigns and end-to-end MCA leads generation services bound to bring best, exceptional results for our shoppers.

Bhuvana said...

You have completed certain reliable points there. I did some research on the subject and found that almost everyone will agree with your blog.

Data Science Training in Hyderabad

Data Science Training in Hyderabad said...

Good work, unique site and interesting too… keep it up…looking forward for more updates. Good luck to all of you and thanks so much for your hard-work…

Data Science Training in Hyderabad

traininginstitute said...

Your work is very good and I appreciate you and hopping for some more informative posts
data science training

training institute said...

This post is very simple to read and appreciate without leaving any details out. Great work!
data scientist training in malaysia

pujari ashwini said...

This was a terrific piece of content in my opinion. Thank you so much for your contribution, and please keep sharing what you know.

digital marketing training in hyderabad
digital marketing course in ameerpet

Ramesh Sampangi said...

AI Patasala is the most rumored Python Training in Hyderabad developed to help you advance your career with a massive increase in the latest technology.
AI Patasala Python Course

Sneha Cubestech said...

Hey tom

Understanding the latest concepts is possible only through content like this. Thanks for sharing this page here. It will be useful for my future projects as well. Keep blogging articles like this.

Mobile app development company
Best web development company
Best Software Development company

traininginstitute said...

I really thank you for the valuable info on this great subject and look forward to more great posts
data scientist course in malaysia

BK-25 said...

Very Informative blog thank you for sharing. Keep sharing.

Best software training institute in Chennai. Make your career development the best by learning software courses.

informatica course in chennai
android training in chennai
power bi training in chennai
Docker Training in Chennai
ios training in chennai
Xamarin Training in Chennai
msbi training in chennai

Soureessay said...

Nicely done article.online assignment help in london

Maneesha said...

I really enjoyed reading this post, big fan. Keep up the good work and please tell me when can you publish more articles or where can I read more on the subject?
business analytics course in hyderabad

traininginstitute said...

A great website with interesting and unique material what else would you need.
cyber security course in malaysia

Unknown said...


Nice blog thank you .For your Sharing It's a pleasure to read your post.It's full of information I'm looking for and I'd like to express that "The content of your post is awesome"

software testing training in chennai
ccna training in chennai
javascript training in chennai

careful Bolger said...

Whatsapp Number Call us Now! 01537587949
outsourcing in Bangladesh
USA pone web iphone repair USA
USA SEX WEB careful
bd sex video B tex
bd sex video sex video
bd sex video freelancing course

data science said...

It is perfect chance to make a couple of game plans for the future and the opportunity has arrived to be sprightly. I've scrutinized this post and if I may I have the option to need to suggest you some interesting things or recommendations. Perhaps you could create next articles insinuating this article. I have to examine more things about it!

PMP Training in Malaysia said...

http://professionalservicesmarketing.shapingbusiness.com/2012/03/real-cost-of-not-living-your-brand-in.html?showComment=1646808905755#c7897190591683267455

Career Program and Skill Development said...

Venture into the world of opportunities with Data Science in Bangalore and learn the valuable skills to demonstrate your capabilities to tackle this evolution of huge data. Avail benefits like Placement Assistance, Mock Interview, and Resume Building support from the placement team. Enroll now and learn Python, Tableau, SQL, Hadoop, and Spark to become a specialist in Data Science.


Best Data Science Training institute in Bangalore

Professional Academic Institute said...

Data Science is a booming field with ample job opportunities. Start your preparation today with 360DigiTMG and become a Data Scientist in the right way.


Data Science Course in Jaipur

Career Academic institute said...

Learn to perform Data Mining, Data Cleansing, Data Exploring, Feature Engineering, Prediction Model, and Data Visualization with the Data Science coaching in Bangalore. Learn to extract business-focused insights from data with the help of mathematics and statistics. Hone your skills with the combined pedagogy approach in classrooms and extensive student-faculty interaction that helps identify students for our internship program giving you the feel of a real-world professional environment.

Business Analytics Course in Jodhpur

data science course in gorakhpur said...

Our Data Science certification training with a unique curriculum and methodology helps you to get placed in top-notch companies.
data analytics course in gorakhpur

Let2know said...

This text gives the light wherein we can check the authenticity out. this is extremely quality one and offers indepth guidance. much thanks to you for this decent article.! Windows 7 Ultimate Activation Key

OfHope said...

It is stated that the United Nations Convention on the Law of the Sea (UNCLOS) does not provide a sufficient foundation for the governance of the Arctic due to the fact that the United States Senate has not yet ratified the Convention and that UNCLOS was not created with the Arctic and its problems in mind. Additionally, "specifically formulated multilateral norms and regulations" have not yet been implemented to govern the Arctic because it was never imagined that this region would become a waterway or a place where people could make money. This is one of the reasons why the Arctic has not yet been regulated. Given that this is now the case, the structure of the institutions themselves will need to be revised. The month of March 2009

OfHope said...

It is stated that the United Nations Convention on the Law of the Sea (UNCLOS) does not provide a sufficient foundation for the governance of the Arctic due to the fact that the United States Senate has not yet ratified the Convention and that UNCLOS was not created with the Arctic and its problems in mind. Additionally, "specifically formulated multilateral norms and regulations" have not yet been implemented to govern the Arctic because it was never imagined that this region would become a waterway or a place where people could make money. This is one of the reasons why the Arctic has not yet been regulated. Given that this is now the case, the structure of the institutions themselves will need to be revised. The month of March 2009, Essay writing service US six groups of Parliamentarians put forward a motion for a resolution on an international treaty to protect the Arctic. They said that "geopolitical neutralization of the region would allow circumpolar nations to work together more" and that this could be done with an Arctic Treaty (European Parliament,2009). This call for a governance approach that includes everyone makes sense when you consider that it might be better for the EU than the current law of the sea approach that the five littoral states prefer.

Hi Every One said...

Took me length to door all the explanation, but I in all actuality partook in the article. It ended up being Very respecting me still up in the air to all the analysts here! Its consistently accessible through now you can't unmarried-handedly be educated, yet with engaged! Free Download Regcure Pro

SrisLawyers said...

I Like your post. It gives more information to us.
Sex Crimes Lawyer VA

Sruthi Karan said...

I really appreciate your valuable efforts and it was very helpful for me. Thank you so much...!
Uncontested Divorce in VA
VA Uncontested Divorce

Mahil mithu said...

Very innovative post! This post is very interesting and thanks for sharing it with us...
Divorce Lawyer in Virginia
How to get a Divorce in VA

Maya said...

The information on this site is more useful. Also, thanks for your help.
ocean of game

shazam said...

Wonderful to read this articles
Dinwiddie Traffic Lawyer
Traffic Lawyer Dinwiddie , VA

Online Shiksha | Online Tuition Classes and Education Tips said...

First of all, I would like to thank you for sharing this great piece of content.
Math is one of the most important subjects for any student in any class. Mathematics is a subject that includes topics such as knowledge of numbers, shapes, spaces, volume, distance etc. It is seen that some students find math interesting, on the other hand some students find math as difficult. This is because most of the students take Maths Online Tuition classes from the starting of their session so that they can score good grades.
The Ultimate Guide to Stars and the Milky Way

Unknown said...

This is wonderful and thank you for educating us. We provide high quality essay writing services to struggling students. Our experts do not leave anything at chance by delivering well-researched and written work on any topic.

Anonymous said...

Great post on "Operator Overloading" in Scala, thanks for sharing valuable information. keep posted Software Testing Classes in Pune

chitra reddy said...

I found the section on statistical analysis and hypothesis testing in this article data analyst course fees in chennai
to be informative and well-explained.

Emma White said...

Operator overloading, like intricate game mechanics, exemplifies the complexity and precision found in gaming development. Gaming Companies in Los Angeles expertly manipulate code to enhance player experiences, showcasing innovation and technical prowess.