Skip to content

Add code tabs for _tour/polymorphic-methods #2554

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions _tour/polymorphic-methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Methods in Scala can be parameterized by type as well as value. The syntax is si

Here is an example:

{% tabs polymorphic-methods_1 class=tabs-scala-version %}
{% tab 'Scala 2' for=polymorphic-methods_1 %}
```scala mdoc
def listOfDuplicates[A](x: A, length: Int): List[A] = {
if (length < 1)
Expand All @@ -26,6 +28,20 @@ def listOfDuplicates[A](x: A, length: Int): List[A] = {
println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)
```
{% endtab %}
{% tab 'Scala 3' for=polymorphic-methods_1 %}
```scala
def listOfDuplicates[A](x: A, length: Int): List[A] =
if length < 1 then
Nil
else
x :: listOfDuplicates(x, length - 1)

println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)
```
{% endtab %}
{% endtabs %}

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 list of duplicates returned by the recursive call. (Note that `::` means prepend an element on the left to a list on the right.)

Expand Down