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 myRange.foreach(println)
Scala is creating a Range
object directly from two Int
s, 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 = a.to(b)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 Int
s into RichInt
s.
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.
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!
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)
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 } }
40 comments:
Very nice example, clearly explained. Thanks
Very helpful, thanks!
First - great demo, I was able to follow it and learn implicit conversions.
Could you also do a section on implicit parameters?
Exquisitely professional thoughts.http://essay-writings-services.com/ 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
Thanks, perfectly written and very helpful.
Excellent, explained very simply, thanks!
Check out this blog post to see how implicit conversions can be used for implementing the Adapter pattern - http://maxondev.com/adapter-design-pattern-scala-implicits/
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.
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 triedhttp://dissertationwriting.services/ for any academic needs? Any reviews, feedbacks, testimonials?
Thank you, a very good post.
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
Thank you. A very nice explanation
Thank you. A very nice explanation
Clear.. Thank you !
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.
Thank you for sharing this informative post.MyAssignmenthelp.com 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.
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
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
CLICK BELOW TO ACCESS STORE>>>
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)
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
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.
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.
Very good write-up. I certainly love this website. Thanks! Walmartmoneycard Register
Very good write-up. I certainly love this website. Thanks! activate.searscard
Accounting and Finance for Banking Syllabus:
Module A and module B are the most important models in accounting and Finance for banking. Among module A and module B, module A is more scoring as compared to module B.
Chapter wise priority for Module A:
Depreciation and its accounting
Foreign exchange arithmetic
Calculation of yield to maturity
Capital budgeting
Calculation of interest and annuities
IIBF JAIIB AFB Syllabus JAIIB AFB Exam Study Material
Nice information, valuable and excellent content. lots of great information and inspiration. Want know about Advanced digital marketing training in Noida
Good post Coursewok help Los Angeles
With the possible exception of the remark that "Rotterdam is the world's largest port," the statement that I have heard more times than any other in my life is that "shipping is an international industry," which I believe is correct. cheap essay paper writers Both statements are, of course, correct. When it comes to national enforcement homework help Canada with laws and regulations, the results are generally favorable; for example, when a manufacturing chimney pollutes the air, the police are called, and the resulting fines can be rather substantial. Maritime Science Dissertation Writing Service UK However, regulations are difficult to develop and enforce on a global scale since they are easily circumvented and are incredibly tough to police. Help in Engineering logistics assignment homework. Aside from that, if international regulations are not consistently followed, they can result in distortions of the competitive environment.
A good SOP writing service will offer many different services for their clients, including editing, proofreading, and formatting. They also offer other services such as resume writing and cover letters for those looking for more assistance in their job search. The Best SOP Writing Services in India can help you write an essay that is sure to stand out from the crowd.
We are a group of freelancer makeup artists in Chandigarh We provide makeup services for film, events, weddings, and other occasions.
This is so good. I learned so much from this. Infact. this helped me a lot in understating my homework as I was having a problem in it. Now it's time to avail https://www.vfixphonesandtech.com/ for more information.
The idea of computerized showcasing has developed to turn into a more extensive promoting technique that includes the utilization of computerized innovations, including cell phones, virtual entertainment, the web, portable applications, online business, web examination, and transformation streamlining. We give understudies the chance to find out about the various ways they can involve the web for advertising items and administrations.saidigitaltraining
Your article is a big help for me. Please keep sharing the solution to problems like this. Now it's time to get Telemarketing Services click for more information.
Wonderful blog. I found this as an informative and captivating post, so I think it is very helpful and acquainted. Now it's time to avail solar in texas for more information.
thanks for sharing
Best Cloud Hosting Server In India
Digi uprise Institute is an intensive programme that will train you in the fundamentals of marketing. It doesn't matter if you're new in the field or are a veteran marketer this course will aid you learn and implement the most effective marketing strategies. It will also teach you how to use state-of-the-art tools for expanding your market reach.The curriculum is taught in an engaging approach, enabling them to apply their skills in real-time. This program is designed to help those with a keen eye and an artistic ability, who wish to advance in their careers.
Assignment Help Australia
Australia offers a wide range of services that may be tailored to each student's needs. These comprise study materials designed especially for more than 75 programmes. You can also pay experienced writers to edit your writings.
I was searching to read that kind of article and I finally found it. I am very happy to see your article after a long time. Nice post. Now its time to avail boise airport shuttle for more information.
thanks for sharing Fruit Packaging Box
Post a Comment