DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Trending

  • Measuring the Impact of AI on Software Engineering Productivity
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  1. DZone
  2. Coding
  3. Languages
  4. Implicit Conversions in Scala

Implicit Conversions in Scala

By 
Tom Jefferys user avatar
Tom Jefferys
·
Apr. 28, 12 · Interview
Likes (6)
Comment
Save
Tweet
Share
26.8K Views

Join the DZone community and get the full member experience.

Join For Free

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 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 = 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 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
        
  }
 
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Scala (programming language)

Published at DZone with permission of Tom Jefferys, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!