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

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
\n", "\n", "# Named Arguments\n", "\n", "When calling methods, you can label the arguments with their parameter names like so:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John Smith\n", "John Smith\n", "John Smith\n" ] }, { "data": { "text/plain": [ "defined \u001b[32mfunction\u001b[39m \u001b[36mprintName\u001b[39m" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def printName(first: String, last: String): Unit = {\n", " println(first + \" \" + last)\n", "}\n", "\n", "printName(\"John\", \"Smith\") // Prints \"John Smith\"\n", "printName(first = \"John\", last = \"Smith\") // Prints \"John Smith\"\n", "printName(last = \"Smith\", first = \"John\") // Prints \"John Smith\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how the order of named arguments can be rearranged. However, if some arguments are named and others are not, the unnamed arguments must come first and in the order of their parameters in the method signature." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "cmd1.sc:1: positional after named argument.\n", "val res1 = printName(last = \"Smith\", \"john\") // error: positional after named argument\n", " ^Compilation Failed" ] }, { "ename": "", "evalue": "", "output_type": "error", "traceback": [ "Compilation Failed" ] } ], "source": [ "printName(last = \"Smith\", \"john\") // error: positional after named argument" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that named arguments do not work with calls to Java methods.\n", "

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 }