Skip to content

Commit d0cd123

Browse files
authored
Merge pull request #740 from travissarles/polymorphicmethods
Rewrote polymorphic methods tour
2 parents 96f2386 + de689b1 commit d0cd123

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

tutorials/tour/_posts/2017-02-13-polymorphic-methods.md

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,29 @@ disqus: true
66

77
tutorial: scala-tour
88
categories: tour
9+
section:
910
num: 28
1011

1112
next-page: local-type-inference
1213
previous-page: implicit-conversions
14+
prerequisite-knowledge: unified-types,
1315
---
1416

15-
Methods in Scala can be parameterized with both values and types. Like on the class level, value parameters are enclosed in a pair of parentheses, while type parameters are declared within a pair of brackets.
17+
Methods in Scala can be parameterized by type as well as value. The syntax is similar to that of generic classes. Type parameters are declared within a pair of brackets while value parameters are enclosed in a pair of parentheses.
1618

1719
Here is an example:
1820

1921
```tut
20-
def dup[T](x: T, n: Int): List[T] = {
21-
if (n == 0)
22-
Nil
23-
else
24-
x :: dup(x, n - 1)
22+
def listOfDuplicates[A](x: A, length: Int): List[A] = {
23+
if (length < 1)
24+
Nil
25+
else
26+
x :: listOfDuplicates(x, length - 1)
2527
}
26-
27-
println(dup[Int](3, 4))
28-
println(dup("three", 3))
28+
println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
29+
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)
2930
```
3031

31-
Method `dup` is parameterized with type `T` and with the value parameters `x: T` and `n: Int`. In the first call to `dup`, the programmer provides the required parameters, but as the following line shows, the programmer is not required to give actual type parameters explicitly. The type system of Scala can infer such types. This is done by looking at the types of the given value parameters and at the context where the method is called.
32+
The method `listOfDuplicates` takes a type parameter `A` and values parameters `x` and `n`. In this case, 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 to `listOfDuplicates`. (note: `::` means prepend an element on the left to a sequence on the right).
33+
34+
When we call `listOfDuplicates` with `[Int]` as the type parameter, the first argument must be an int and the return type will be List[Int]. However, you don't always need to explicitly provide the the type parameter because the compiler can often figure it out based on the type of value argument (`"La"` is a String). In fact, if calling this method from Java it is impossible to provide the type parameter.

0 commit comments

Comments
 (0)