← Back to Scala Course | Chapter 12: Advanced Features | Lesson 1 of 7

Implicit Parameters

An implicit parameter is an input Scala fills in for you automatically, like a waiter who brings your usual order without you asking. You just need one such value to be in view.

In this page:

  1. Implicit Parameters
Syntax
scala
def function_name(param: Type)(implicit name: Type): ReturnType = expression

implicit val name: Type = value
function_name(arg)

Implicit Parameters

An implicit parameter lets the compiler automatically supply an argument from an in-scope implicit val/def, if the caller doesn't provide one explicitly.

This is commonly used for passing along contextual configuration, like a formatting rule or execution context, without threading it explicitly through every call. Only one implicit value of a given type can be in scope at a time without ambiguity errors.

Note: If the compiler reports 'could not find implicit value', it means no matching implicit definition is in scope for that parameter's type.

Example: Implicit Parameters

markup
object Main extends App {
  implicit val defaultGreeting: String = "Hello"

  def greet(name: String)(implicit greeting: String): Unit = {
    println(s"$greeting, $name!")
  }

  greet("Alice") // uses the implicit defaultGreeting
  greet("Bob")("Hi") // explicitly overridden
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Defining two implicit values of the same type in scope, causing an ambiguous implicit values error.
  2. Forgetting that the implicit parameter list must be last, as in def greet(name: String)(implicit greeting: String).
  3. Using implicit for everything, which makes it hard to see where values come from; Scala 3 uses given and using.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.