Thursday, 10 November 2011

Implicit Conversions in Scala

Following on from the previous post on operator overloading I'm going to be looking at Implicit Conversions, and how we can combine them to with operator overloading to do some really neat things, including one way of creating a multi-parameter conversion.

So what's an "Implicit Conversion" when it's at home?

So lets start with some basic Scala syntax, if you've spent any time with Scala you've probably noticed it allows you to do things like:

   (1 to 4).foreach(println) // print out 1 2 3 4 

Ever wondered how it does this? Lets make things more explicit, you could rewrite the above code as:

    val a : Int = 1
    val b : Int = 4
    val myRange : Range = a to b

Scala is creating a Range object directly from two Ints, and a method called to.

So what's going on here? Is this just a sprinkling of syntactic sugar to make writing loops easier? Is to just a keyword in like def or val?

The answers to all this is no, there's nothing special going on here. to is simply a method defined in the RichInt class, which takes a parameter and returns a Range object (specifically a subclass of Range called Inclusive). You could rewrite it as the following if you really wanted to:

   val myRange : Range =

Hang on though, RichInt may have a "to" method but Int certainly doesn't, in your example you're even explicitly casting your numbers to Ints

Which brings me nicely on to the subject of this post, Implicit Conversions. This is how Scala does this. Implicit Conversions are a set of methods that Scala tries to apply when it encounters an object of the wrong type being used. In the case of the to example there's a method defined and included by default that will convert Ints into RichInts.

So when Scala sees 1 to 4 it first runs the implicit conversion on the 1 converting it from an Int primitive into a RichInt. It can then call the to method on the new RichInt object, passing in the second Int (4) as the parameter.

Hmm, think I understand, how's about another example?

Certainly. Lets try to improve our Complex number class we created in the previous post.

Using operator overloading we were able to support adding two complex numbers together using the + operator. eg.

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

But what if we want to support adding a normal number to a complex number, how would we do that? We could certainly overload our "+" method to take a Double argument, ie something like...

    def +(n: Double) = new Complex(this.real + n, this.imag)

Which would allow us to do...

    val sum = myComplexNumber + 8.5

...but it'll break if we try...

    val sum = 8.5 + myComplexNumber

To get around this we could use an Implicit Conversion. Here's how we create one.

  object ComplexImplicits {
    implicit def Double2Complex(value : Double) = 
                                     new Complex(value,0.0) 

Simple! Although you do need to be careful to import the ComplexImplicits methods before they can be used. You need to make sure you add the following to the top of your file (even if your Implicits object is in the same file)...

   import ComplexImplicits._

And that's the problem solved, you can now write val sum = 8.5 + myComplexNumber and it'll do what you expect!

Nice. Is there anything else I can do with them?

One other thing I've found them good for is creating easy ways of instantiating objects. Wouldn't it be nice if there were a simpler way of creating one of our complex numbers other than with new Complex(3.0,5.0). Sure you could get rid of the new by making it a case class, or implementing an apply method. But we can do better, how's about just (3.0,5.0)

Awesome, but I'd need some sort of multi parameter implicit conversion, and I don't really see how that's possible!?

The thing is, ordinarily (3.0,5.0) would create a Tuple. So we can just use that tuple as the parameter for our implicit conversion and convert it into a Complex. how we might go about doing this...

  implicit def Tuple2Complex(value : Tuple2[Double,Double]) = 
                               new Complex(value._1,value._2);

And there we have it, a simple way to instantiate our Complex objects, for reference here's what the entire Complex code looks like now.

import ComplexImplicits._

object ComplexImplicits {
  implicit def Double2Complex(value : Double) = new Complex(value,0.0) 

  implicit def Tuple2Complex(value : Tuple2[Double,Double]) = new Complex(value._1,value._2);


class Complex(val real : Double, val imag : Double) {
  def +(that: Complex) : Complex = (this.real + that.real, this.imag + that.imag)
  def -(that: Complex) : Complex = (this.real - that.real, this.imag + that.imag)
  def unary_~ = Math.sqrt(real * real + imag * imag)
  override def toString = real + " + " + imag + "i"

object Complex {
  val i = new Complex(0,1);
  def main(args : Array[String]) : Unit = {
       var a : Complex = (4.0,5.0)
       var b : Complex = (2.0,3.0)
       println(a)  // 4.0 + 5.0i
       println(a + b)  // 6.0 + 8.0i
       println(a - b)  // 2.0 + 8.0i
       println(~b)  // 3.60555
       var c = 4 + b
       println(c)  // 6.0 + 3.0i
       var d = (1.0,1.0) + c  
       println(d)  // 7.0 + 4.0i



Unknown said...

Very nice example, clearly explained. Thanks

winnetou said...

Very helpful, thanks!

Anonymous said...

First - great demo, I was able to follow it and learn implicit conversions.

Could you also do a section on implicit parameters?

Unknown said...

Exquisitely professional thoughts. I merely hit upon this web site and desired to enunciate that I've definitely delighted in reckoning your blog articles or blog posts. Rest assured I'll subsist pledging to your RSS and I wish you write-up after much more shortly

Unknown said...

Thanks, perfectly written and very helpful.

Unknown said...

Excellent, explained very simply, thanks!

M@)(im said...

Check out this blog post to see how implicit conversions can be used for implementing the Adapter pattern -

aliyaa said...

You should not worry about huge data entry problem because we have now online data entry service that will solve your problem within a minutes. said...

This is so complicated for me. To be honest with you, I am so far from all this... but my dissertation should be completed in two weeks. Have you ever tried​ for any academic needs? Any reviews, feedbacks, testimonials?

Unknown said...

Thank you, a very good post.

Curtis said...

I really enjoyed how amazingly you noticed the micro changes and wrote them in broader way. Management Information Systems Assignment. I found this as an informative and captivating post, so I think it is very helpful and acquainted. I would like to thank you for the endeavor you have made in this piece. Business Assignments Writing

Amit said...

Thank you. A very nice explanation

Amit said...

Thank you. A very nice explanation

Unknown said...

Clear.. Thank you !

Angel Claudia said...

All our already written essay services that we pe to the client are assessed for high quality and any other issues that could affect the client’s grade.

meldaresearch said...

Our writing company is the most best online essay writing services company and we are always ready to answer any form of questions which may come up especially those seeking for how to write my research paper cheap.

Latest and Upcoming Govt Jobs in India said...

Uttar Pradesh Education Board will release the application form of UP BTC. We will provide our readers all-important links of UP BTC 2020 on our page. To fill UP BTC online Application form 2020 candidates will require bachelor degree from any discipline. Application Form will available on the official website of UP Deled.

meldaresearch said...

We assure you that all the best essay writers online, custom college papers, research papers and term papers that we deliver to our clients are the best in the industry and you do not need to have a second thought when buying any of our cheap paper writing service from us.

Kevin said...

Amazing news for all those who are interested in applying for TNFUSRC Exam. The forest watcher declaration form are released now.
All the interested candidates can apply now by visitng our website.
All the best.

meldaresearch said...

The quality of our Best Essay Writing Service are always high as we work hard to ensure that we uphold our good reputations at all time. We make sure that Nursing Essay Writing Services ordered are delivered on time and our prices are affordable to every student. said...

Thank you for sharing this informative is giving dissertation conclusion help to students.we are already trusted by thousands of students who struggle to write their academic papers and also by those students who simply want Cost of Capital Assignment Help Online to save their time and make life easy.

Term Paper Writing Services said...

It is very convenient to use Admission Essay Writing Service of Research Papers Writing Services company which is available at any time of the day of the week, month and year as it can assist you any time you require Custom College Papers Writing Services.

Ivymelda said...

Custom Research Papers Writing Services are relatively fast and convenient. Also the company offers Academic Essay Writing Services and any student can request from us the best Custom Research Paper Writing Services.

Legitimate Custom Research Paper Services said...

Are you looking for Unmatched Legitimate Custom Research Paper Services? You don’t need to fail your Custom Research Paper Writing Services when you can utilize the best Dissertation Help Services or Affordable Custom Research Paper Services from the help of the online paper writers.

Academic Assignment Writing said...

I enjoy kinds very own post. It will be respectable to get a single narrative inside and outside of the core of this distinctive core specialized niche will likely be commonly knowledgeable.
best online assignment help

Expo 2020 said...

Hope you will keep on offering good content like this more often. I feel more and more people should know about this. Also, I agree on most of the points you have made.
Ikea dubai

Sam said...

For those students who are stuck with their College or University Assignments and are in desperate need of some professional assignment writing services, then My Assignment Help is the place you want to be because our experts have the knowledge, skills, and experience to help college and university students with their research papers, essays, case studies and Thesis projects

Tanjila Akter said...

Really amazing content, thanks for sharing with us and keep updating! This website article is really excellent and unique. I will visit your site again. You can see the Bangladesh Education, Events, JSC, PSC, SSC, HSC, Honours, nu, Result, routine and Job circular Pureinfobd

Gerard said...

Nice post! Thanks for sharing this information. Looking for help with thesis or dissertation data analysis? Get online qualitative and quantitative data analysis services from the leading Research Projects Writing Company at an affordable cost. Our experts are available 24/7.

Ducat said...

Ducat is one of the sap training institute in noida with 100% placement support. Ducat has well defined course modules and training sessions for students. At Ducat ERP SAP training is conducted during day time classes, weekend classes, evening batch classes and fast track training classes.

sap training institute in noida


Gerard said...

Nice post! Thanks for sharing this information. Looking for help with your selecting your thesis topic? Get reliable research topics help from the leading Research Projects Writing Company at an affordable cost. Our experts are available 24/7.

Sam Finnie said...

Helping out students to carry out their Marketing Assignments

admin said...

Buy medicines without a prescription near you?, we are here to give a quick solution. At our secured pharmacy, you will be able to conveniently purchase your medicines and other healthy merchandise securely, Legit and Fast, We sell only Branded medications PHARMACY GRADE

PHARMACY STORE CRYPTOCURRENCY PAYMENTS ONLY -  Oxycodone 30 mg near you  No Prescription | how to get 30 mg Adderall XR in us  |  pharmacy grade Subutex 8 mg | Dsuvia 30Mcg strongest painkiller on earth | where to get Subutex 8 mg Online in USA | Suboxone Online 8 mg Buy | OC Oxycontin near you Mundi pharma for sale 80 mg, Hydrocodone on sale here, Stealth buy Oxycontin OC in USA | Where Drugs are original? | Dilaudid 8 mg side effects |, How long till delivery in USA ? Bitcoins, ethereum , Bitcoins cash | Buy dsuvia 30mcg Online | TRUSTED AND DISCREET
We offer: 
* High-Quality Pharmacy Grade Medicines. 
* Best and Affordable prices. 
* Fast and Stealth delivery - Tracking Available! 
* Buy Direct and Save Time with Cryptocurrency 
* Reshipment is offered if the package does not get to location or refunds 
* Various Discreet Shipping options depending on location
* No Prescription Required (NO RX) 

TN Hindi said...

Your post is very great.i read this post this is a very helpful. i will definitely go ahead and take advantage of this. You absolutely have wonderful stories.Cheers for sharing with us your blog
AWS Cloud Security

kavyagaur said...

Your post is very great.i read this post this is a very helpful. i will definitely go ahead and take advantage of this. You absolutely have wonderful stories.Cheers for sharing with us your blog. python training in noida

James Ian said...

Your article is attractive and informative. Nursing Care Plan Writing Services is a platform that offers high quality and competent services. All our writers have a nursing background which helps to ensure quality. Different writers have specialized in different nursing areas. Our team will, therefore, work nursing care plans for patients with different diagnoses to perfection. They then provide you with the intervention measures to use in the patient care procedure. Learn more from Nursing Care Plan Writing Services.

James Ian said...

Exactly what i was looking for. Struggling to complete Python assignments on your own? No need to worry any further! We have a team of skilled Python assignment help programmers who can help you complete any Python assignment with ease. Our programming experts leverage their in-depth programming experience to provide the best-in-class help in Python coding. We have been offering quality Python assignment help to students residing in the UK, US, Canada, Australia and other countries over the years. Get Python Homework Help

Daniel hobart said...

Do You Want To Be The Best At Book report writing? Book report writing seems a nerve-wracking affair, isn’t it so? Online assignment help from the best online book writers in Australia

Navdrill said...

Below are few Things you might be looking for latest updates on Musics, Movies and Videos
Click Here for


assignment help australia said...

Assignment help Adelaide is an online writing services provider platform we offer writing services at affordable and cheap prices. Try our best services and get full satisfaction from our side.

Masonethan said...

As a student you might not be able to write the assignment on your own then I recommend you getting the humanities assignment help from a reliable service provider like us.

Activatecard said...

Very good write-up. I certainly love this website. Thanks! Walmartmoneycard Register

Very good write-up. I certainly love this website. Thanks! activate.searscard