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

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
\n", "\n", "# Nested Methods\n", "\n", "In Scala it is possible to nest method definitions. The following object provides a `factorial` method for computing the factorial of a given number:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Factorial of 2: 2\n", "Factorial of 3: 6\n" ] }, { "data": { "text/plain": [ "defined \u001b[32mfunction\u001b[39m \u001b[36mfactorial\u001b[39m" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ " def factorial(x: Int): Int = {\n", " def fact(x: Int, accumulator: Int): Int = {\n", " if (x <= 1) accumulator\n", " else fact(x - 1, x * accumulator)\n", " } \n", " fact(x, 1)\n", " }\n", "\n", " println(\"Factorial of 2: \" + factorial(2))\n", " println(\"Factorial of 3: \" + factorial(3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The output of this program is:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "Factorial of 2: 2\n", "Factorial of 3: 6\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 }