{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "Tour of Scala
\n", "\n", "\n", "# By-name Parameters\n", "\n", "_By-name parameters_ are only evaluated when used. They are in contrast to _by-value parameters_. To make a parameter called by-name, simply prepend `=>` to its type." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "data": { "text/plain": [ "defined \u001b[32mfunction\u001b[39m \u001b[36mcalculate\u001b[39m" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def calculate(input: => Int) = input * 37" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By-name parameters have the advantage that they are not evaluated if they aren't used in the function body. On the other hand, by-value parameters have the advantage that they are evaluated only once.\n", "\n", "Here's an example of how we could implement a while loop:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "1\n" ] }, { "data": { "text/plain": [ "defined \u001b[32mfunction\u001b[39m \u001b[36mwhileLoop\u001b[39m\n", "\u001b[36mi\u001b[39m: \u001b[32mInt\u001b[39m = \u001b[32m0\u001b[39m" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def whileLoop(condition: => Boolean)(body: => Unit): Unit =\n", " if (condition) {\n", " body\n", " whileLoop(condition)(body)\n", " }\n", "\n", "var i = 2\n", "\n", "whileLoop (i > 0) {\n", " println(i)\n", " i -= 1\n", "} // prints 2 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The method `whileLoop` uses multiple parameter lists to take a condition and a body of the loop. If the `condition` is true, the `body` is executed and then a recursive call to whileLoop is made. If the `condition` is false, the body is never evaluated because we prepended `=>` to the type of `body`.\n", "\n", "Now when we pass `i > 0` as our `condition` and `println(i); i-= 1` as the `body`, it behaves like the standard while loop in many languages.\n", "\n", "This ability to delay evaluation of a parameter until it is used can help performance if the parameter is computationally intensive to evaluate or a longer-running block of code such as fetching a URL.\n", "\n", "\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 }