×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Where does Scala look for implicit?

By IncludeHelp Last updated : November 16, 2024

Scala Implicit Parameters

Implicit parameters in Scala are predefined values that can be used in case no parameters are provided while calling the method.

There are various type of implicit parameters and based on its type the Scala compiler looks for the values of implicit parameters when required.

Where Implicit's Come From?

The Scala compiler looks for an implicit value in the lexical scope or implicit scope of the program.

Here are some places where implicit values can be found:

  1. Lexical Scope
  2. Implicit Scope
  3. Companion Scope
  4. Implicit Scope of arguments type
  5. Implicit Scope of type arguments
  6. Outer object for the nested Type
  7. Package Object

Implicit defined in Lexical Scope

When compiler needs an implicit value, it looks for a value of the same type defined as implicit.

Syntax for creating an implicit value

Program to illustrate the call to implicit values in lexical scope

object MyClass {
  implicit val b: Int = 10
  
  def addValues(a: Int)(implicit b: Int): Int = a + b

  def main(args: Array[String]): Unit = {
    println("Calling function with implicit value " + addValues(4))
  }
}

Output

Calling function with implicit value 14

Implicit Values defined in Implicit Scope

Implicit scope is added in order to avoid usage of extra imports by including an implicit Companion Object of a type.

Implicit Scope of Type Arguments

Implicit scope of type arguments are found when the compiler finds an implicit value in the scope of type arguments like in companion Objects.

This companion objects can be found in multiple places in the program,

Looking for companion Object in Outer Objects of Nested Type

The implicit values for nested values can be found in the objects other than the object itself. These can define values that can be used and implicit.

This outer object can be found in other packages too, that can be used to avoid lexical scope value of implicit calls.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.