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

  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech

Trending

  • How to Convert XLS to XLSX in Java
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • Recurrent Workflows With Cloud Native Dapr Jobs
  1. DZone
  2. Coding
  3. Languages
  4. How Does "20 Seconds" Work in Scala?

How Does "20 Seconds" Work in Scala?

This article will show you how a seemingly magical expressions work, and how you can build your own.

By 
Daniel Ciocirlan user avatar
Daniel Ciocirlan
·
Aug. 11, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
7.3K Views

Join the DZone community and get the full member experience.

Join For Free
This short article will show you how apparently magical constructs like 20.seconds works in Scala, although the Int type doesn't have such methods natively.

This article will make more sense if you know the basics of implicits, but then again, if you do know how implicits work, there's only one step to understanding how these seemingly magical methods work, so I'll cover everything you need to know.

You can read this article over at Rock the JVM or watch it on YouTube or in the video below: 


1. The "Problem"

The question we're addressing here is the following: the Int type has a very small set of methods and certainly the seconds method isn't one of them:
Scala
xxxxxxxxxx
1
 
1
val womp = 20.seconds // compile error: symbol "seconds" not found

However, once we add a special import, it magically works:
Scala
xxxxxxxxxx
1
 
1
import scala.concurrent.duration._
2
3
val aDuration = 20.seconds // works!

So how does the magical import work?

2. Enriching Types

The answer is not in the import itself, but in what's imported — the types and values that are imported might as well be in scope, and methods like .seconds would work just as fine. It's their structure that provides the magic. To understand how they work, we need to go back to implicits.

I'm not going to talk about all the functionality that the implicit keyword does in Scala — we'll probably do that in another article — but we are going to focus on one kind of implicits: implicit classes. Implicit classes are one-argument wrappers, i.e. a class with one constructor argument, with regular methods, fields, etc, except that they have the implicit keyword in their declaration:
Scala
xxxxxxxxxx
1
 
1
implicit class MyRichString(string: String) {
2
  def fullStop: String = string + "."
3
}

If we removed the implicit keyword there, this would be a pretty uninteresting class. Adding implicit will add some special powers. We can either say
Scala
xxxxxxxxxx
1
 
1
new MyRichString("This is a sentence").fullStop

or this:
Scala
xxxxxxxxxx
1
 
1
"This is a sentence".fullStop

This works although the fullStop method doesn't exist for the String class. Normally, the code would not compile, but the compiler will add an extra step of searching for any implicit wrapping or conversion of a String value that might have the fullStop method, which in our case it does. So in reality, the compiler will rewrite our last call as
Scala
xxxxxxxxxx
1
 
1
// "This is a sentence".fullStop beecomes:
2
new MyRichString("This is a sentence").fullStop

which is what we (explicitly) wrote earlier. This pattern provides what we call extension methods - libraries like Cats use this all the time.

3. Importing

If an implicit class like this is not written in the scope where we use the "magical" method, the code will not compile until we bring that implicit class into scope. This means an import. Usually, libraries (including the standard library) packs implicits into "Ops"-like objects:
Scala
xxxxxxxxxx
1
 
1
package mylibrary
2
3
object MyStringOps {
4
    implicit class MyRichString(string: String) {
5
      def fullStop: String = string + "."
6
    }
7
}

and then later in our code, when we import it, we'll also have access to the extension method:
Scala
xxxxxxxxxx
1
 
1
import mylibrary._
2
3
"Starting to get it".fullStop

The Scala duration package works in the same way: when you import scala.concurrent.duration._ you gain access to extension methods on the Int type that returns instances of Duration:
Scala
xxxxxxxxxx
1
 
1
import scala.concurrent.duration._
2
20.seconds
3
500.millis


4. A Bit More and Conclusion

Some packages are automatically imported with every Scala code. Some of these packages might include extension methods like the .seconds one. Ever wondered how things like
Scala
xxxxxxxxxx
1
 
1
val range = 1 to 100

work? With the tools you now have, it's quite easy to understand that there is an implicit conversion that enriches the Int type:
Scala
x
 
1
// some implicit conversion here { ...
2
    def to(end: Int): Range
3
// ... }

You've now learned how extension methods work and how magical things like 20.seconds work in Scala, making them seem like they're part of the language or standard library. This skill will prove useful as you become more experienced with Scala libraries like Cats.

Check out our channel and follow us on Twitter and LinkedIn for lots of free tips and techniques and the video versions of the articles here!
Scala (programming language)

Published at DZone with permission of Daniel Ciocirlan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech

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!