Scala - Implicit Imports



Scala is open to use of implicit imports. It provides streamline coding and improves efficiency. You can use packages and classes to be automatically available without explicitly importing them in your code.

Implicit Imports

Implicit imports in Scala are the default imports. These are automatically included in every Scala source file. These imports include basic packages and classes that are frequently used. So, you do not have to manually import these in every file.

Using Implicit Imports

You do not need to import basic classes like String, Int, and List explicitly in your Scala programs. Because these are available by default due to implicit imports.

object Demo {
   def main(args: Array[String]) = {
      // Using Implicit Imports: String, Int, and List
      val name: String = "Scala"
      val age: Int = 10
      val numbers: List[Int] = List(1, 2, 3, 4, 5)
      
      println(s"Name: $name")
      println(s"Age: $age")
      println(s"Numbers: $numbers")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Name: Scala
Age: 10
Numbers: List(1, 2, 3, 4, 5)

Types of Implicit Imports

There are various implicit imports by default. These imports cover important classes and objects from the Scala standard library. For example, basic types, collections, and utility objects. These are implicit imports in Scala -

  • lang package
  • scala package
  • Predef object
  • collection.immutable
  • math
  • concurrent

We have explained these as follows.

1. java.lang Package

You can use java.lang package that is implicitly imported. So these classes like String, Object, Throwable, Exception, Thread, etc., are available without explicit import.

Example

Following is the example which shows you how to use java.lang classes directly in your Scala code -

object Demo {
   def main(args: Array[String]) = {
      val str: String = "Hello, Scala"
      val thread: Thread = new Thread(new Runnable {
         def run() = println("Running in a thread")
      })
      
      thread.start()
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code uses String and Thread classes from java.lang package without explicit imports.

This will produce the following result -

Running in a thread

2. Scala Package

The scala package includes important Scala classes and objects, like Int, List, Option, Function, and others. These are implicitly available in every Scala source file.

Example

Following is the example which shows you how to use classes from the scala package without explicitly importing these -

object Demo {
   def main(args: Array[String]) = {
      val opt: Option[Int] = Some(5)
      
      opt match {
         case Some(value) => println(s"Value: $value")
         case None => println("No value")
      }
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code uses Option and Some classes from the scala package without explicit imports.

This will produce the following result -

Value: 5

3. Using scala.Predef

The scala.Predef object is automatically imported into every Scala source file. It provides type aliases, implicit conversions, and other utility functions.

Example

Following is the example which shows you how to use utilities from scala.Predef without explicit imports -

object Demo {
   def main(args: Array[String]) = {
      val nums = Array(1, 2, 3)
      
      println(s"Sum: ${nums.sum}")
      println(s"Max: ${nums.max}")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code uses sum and max utility functions from scala.Predef without explicit imports.

This will produce the following result

Sum: 6
Max: 3

4. Using scala.collection.immutable

The scala.collection.immutable package provides immutable collections that are implicitly imported into every Scala source file. These collections include commonly used types like List, Set, and Map, which ensure that once created, their elements cannot be altered.

Example

Following is the example which shows you how to use immutable collections without explicit imports -

object Demo {
   def main(args: Array[String]) = {
      val numbers: List[Int] = List(1, 2, 3, 4, 5)
      val names: Set[String] = Set("Alice", "Bob", "Charlie")
      
      println(s"Numbers: $numbers")
      println(s"Names: $names")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code uses List and Set from scala.collection.immutable without explicit imports.

This will produce the following result -

Numbers: List(1, 2, 3, 4, 5)
Names: Set(Alice, Bob, Charlie)

5. Using scala.math

The scala.math package provides mathematical functions and constants, which are implicitly imported into every Scala source file. This includes functions like sqrt, pow, and constants like Pi.

Example

Following is the example which shows you how to use mathematical functions and constants without explicit imports -

object Demo {
   def main(args: Array[String]) = {
      val radius: Double = 5.0
      val area: Double = scala.math.Pi * scala.math.pow(radius, 2)
      
      println(s"Area of the circle: $area")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code uses Pi and pow from scala.math without explicit imports.

This will produce the following result -

Area of the circle: 78.53981633974483

6. Using scala.concurrent

The scala.concurrent package provides utilities for concurrent programming, including Futures and Promises, which are implicitly imported into every Scala source file. These allow for easy asynchronous programming.

Example

Following is the example which shows you how to use Futures for asynchronous programming without explicit imports -

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object Demo {
   def main(args: Array[String]) = {
      val future = Future {
         Thread.sleep(1000)
         42
      }
      
      future.onComplete {
         case scala.util.Success(value) => println(s"Future completed with value: $value")
         case scala.util.Failure(e) => println(s"Future failed with exception: $e")
      }
      
      // Wait for the future to complete
      Thread.sleep(2000)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

The above code uses Future and ExecutionContext from scala.concurrent without explicit imports.

This will produce the following result -

Future completed with value: 42

Notes

  • Implicit imports in Scala are the default imports. These imports are automatically included in every Scala source file.
  • Implicit imports reduce boilerplate code and are used in classes and objects available without explicit import statements.
  • The java.lang package is implicitly imported. So it provides classes like String, Object, and Thread.
  • The scala package is implicitly imported. So it provides classes and objects like Int, List, and Option.
  • The scala.Predef object is implicitly imported. So you can use implicit conversions, type aliases, and utility functions.
  • The scala.collection.immutable package is implicitly imported. So you can use immutable collections like List, Set, and Map.
  • The scala.math package is implicitly imported. So you can use mathematical functions and constants like sqrt, pow, and Pi.
  • The scala.concurrent package is implicitly imported. So you can use utilities for concurrent programming like Futures and Promises.
Advertisements