You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
18
+
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.
19
19
20
20
Here is an example:
21
21
22
22
```tut
23
-
def listOfDuplicates[A](x: A, length: Int): List[A] = {
24
-
if (length < 1)
25
-
Nil
26
-
else
27
-
x :: listOfDuplicates(x, length - 1)
28
-
}
23
+
def listOfDuplicates[A](x: A, length: Int): List[A] =
The method `listOfDuplicates` takes a type parameter `A` and values parameters `x` and `length`. 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).
32
+
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.)
34
33
35
-
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.
34
+
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]`.
35
+
36
+
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`.
0 commit comments