Skip to content

Commit 0084465

Browse files
authored
Add code tabs for _tour/polymorphic-methods (#2554)
1 parent 8648cbb commit 0084465

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Diff for: _tour/polymorphic-methods.md

+16
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Methods in Scala can be parameterized by type as well as value. The syntax is si
1616

1717
Here is an example:
1818

19+
{% tabs polymorphic-methods_1 class=tabs-scala-version %}
20+
{% tab 'Scala 2' for=polymorphic-methods_1 %}
1921
```scala mdoc
2022
def listOfDuplicates[A](x: A, length: Int): List[A] = {
2123
if (length < 1)
@@ -26,6 +28,20 @@ def listOfDuplicates[A](x: A, length: Int): List[A] = {
2628
println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
2729
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)
2830
```
31+
{% endtab %}
32+
{% tab 'Scala 3' for=polymorphic-methods_1 %}
33+
```scala
34+
def listOfDuplicates[A](x: A, length: Int): List[A] =
35+
if length < 1 then
36+
Nil
37+
else
38+
x :: listOfDuplicates(x, length - 1)
39+
40+
println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
41+
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)
42+
```
43+
{% endtab %}
44+
{% endtabs %}
2945

3046
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.)
3147

0 commit comments

Comments
 (0)