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

Previous

\n", "

Next

\n", "

Tour of Scala

\n", "
\n", "\n", "# Polymorphic Methods\n", "\n", "Methods in Scala can be parameterized by type as well as value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.\n", "\n", "Here is an example:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "attributes": { "classes": [ "tut" ], "id": "" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "List(3, 3, 3, 3)\n", "List(La, La, La, La, La, La, La, La)\n" ] }, { "data": { "text/plain": [ "defined \u001b[32mfunction\u001b[39m \u001b[36mlistOfDuplicates\u001b[39m" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def listOfDuplicates[A](x: A, length: Int): List[A] = {\n", " if (length < 1)\n", " Nil\n", " else\n", " x :: listOfDuplicates(x, length - 1)\n", "}\n", "println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)\n", "println(listOfDuplicates(\"La\", 8)) // List(La, La, La, La, La, La, La, La)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The method `listOfDuplicates` takes a type parameter `A` and value parameters `x` and `length`. Value `x` is of type `A`. If `length < 1` we return an empty list. Otherwise we prepend `x` to the the list of duplicates returned by the recursive call. (Note that `::` means prepend an element on the left to a list on the right.)\n", "\n", "In first example call, we explicitly provide the type parameter by writing `[Int]`. Therefore the first argument must be an `Int` and the return type will be `List[Int]`.\n", "\n", "The second example call shows that you don't always need to explicitly provide the type parameter. The compiler can often infer it based on context or on the types of the value arguments. In this example, `\"La\"` is a `String` so the compiler knows `A` must be `String`.\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 }