{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
\n", "\n", "# Implicit Parameters\n", "\n", "A method can have an _implicit_ parameter list, marked by the _implicit_ keyword at the start of the parameter list. If the parameters in that parameter list are not passed as usual, Scala will look if it can get an implicit value of the correct type, and if it can, pass it automatically.\n", "\n", "The places Scala will look for these parameters fall into two categories:\n", "\n", "* Scala will first look for implicit definitions and implicit parameters that can be accessed directly (without a prefix) at the point the method with the implicit parameter block is called.\n", "* Then it looks for members marked implicit in all the companion objects associated with the implicit candidate type.\n", "\n", "A more detailed guide to where scala looks for implicits can be found in [the FAQ](https://docs.scala-lang.org//docs.scala-lang.org/tutorials/FAQ/finding-implicits.html)\n", "\n", "In the following example we define a method `sum` which computes the sum of a list of elements using the monoid's `add` and `unit` operations. Please note that implicit values can not be top-level." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mclass\u001b[39m \u001b[36mMonoid\u001b[39m\n", "defined \u001b[32mobject\u001b[39m \u001b[36mImplicitTest\u001b[39m" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abstract class Monoid[A] {\n", " def add(x: A, y: A): A\n", " def unit: A\n", "}\n", "\n", "object ImplicitTest {\n", " implicit val stringMonoid: Monoid[String] = new Monoid[String] {\n", " def add(x: String, y: String): String = x concat y\n", " def unit: String = \"\"\n", " }\n", " \n", " implicit val intMonoid: Monoid[Int] = new Monoid[Int] {\n", " def add(x: Int, y: Int): Int = x + y\n", " def unit: Int = 0\n", " }\n", " \n", " def sum[A](xs: List[A])(implicit m: Monoid[A]): A =\n", " if (xs.isEmpty) m.unit\n", " else m.add(xs.head, sum(xs.tail))\n", " \n", " def main(args: Array[String]): Unit = {\n", " println(sum(List(1, 2, 3))) // uses IntMonoid implicitly\n", " println(sum(List(\"a\", \"b\", \"c\"))) // uses StringMonoid implicitly\n", " }\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`Monoid` defines an operation called `add` here, that combines a pair of `A`s and returns another `A`, together with an operation called `unit` that is able to create some (specific) `A`.\n", "\n", "To show how implicit parameters work, we first define monoids `StringMonoid` and `IntMonoid` for strings and integers, respectively. The `implicit` keyword indicates that the corresponding object can be used implicitly.\n", "\n", "The method `sum` takes a `List[A]` and returns an `A`, which takes the initial `A` from `unit`, and combines each next `A` in the list to that with the `add` method. Making the parameter `m` implicit here means we only have to provide the `xs` parameter when we call the method if Scala can find a an implict `Monoid[A]` to use for the implicit `m` parameter.\n", "\n", "In our `main` method we call `sum` twice, and only provide the `xs` parameter. Scala will now look for an implicit in the scope mentioned above. The first call to `sum` passes a `List[Int]` for `xs`, which means that `A` is `Int`. The implicit parameter list with `m` is left out, so Scala will look for an implicit of type `Monoid[Int]`. The first lookup rule reads\n", "\n", "> Scala will first look for implicit definitions and implicit parameters that can be accessed directly (without a prefix) at the point the method with the implicit parameter block is called.\n", "\n", "`intMonoid` is an implicit definition that can be accessed directly in `main`. It is also of the correct type, so it's passed to the sum method automatically.\n", "\n", "The second call to `sum` passes a `List[String]`, which means that `A` is `String`. Implicit lookup will go the same way as with `Int`, but will this time find `stringMonoid`, and passes that automatically as `m`.\n", "\n", "The program will output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "6\n", "abc\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
" ] } ], "metadata": { "kernelspec": { "display_name": "Scala (2.13)", "language": "scala", "name": "scala213" }, "language_info": { "codemirror_mode": "text/x-scala", "file_extension": ".scala", "mimetype": "text/x-scala", "name": "scala", "nbconvert_exporter": "script", "version": "2.13.1" } }, "nbformat": 4, "nbformat_minor": 4 }