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
It is also not compulsory to specify type parameters when [polymorphic methods](polymorphic-methods.html) are called or [generic classes](generic-classes.html) are instantiated. The Scala compiler will infer such missing type parameters from the context and from the types of the actual method/constructor parameters.
The compiler uses the types of the arguments of `MyPair` to figure out what type `A` and `B` are. Likewise for the type of `x`.
44
67
45
68
## Parameters
46
69
47
70
The compiler never infers method parameter types. However, in certain cases, it can infer anonymous function parameter types when the function is passed as argument.
48
71
72
+
{% tabs type-inference_5 %}
73
+
{% tab 'Scala 2 and 3' for=type-inference_5 %}
49
74
```scala mdoc
50
75
Seq(1, 3, 4).map(x => x *2) // List(2, 6, 8)
51
76
```
77
+
{% endtab %}
78
+
{% endtabs %}
52
79
53
80
The parameter for map is `f: A => B`. Because we put integers in the `Seq`, the compiler knows that `A` is `Int` (i.e. that `x` is an integer). Therefore, the compiler can infer from `x * 2` that `B` is type `Int`.
54
81
@@ -58,14 +85,22 @@ It is generally considered more readable to declare the type of members exposed
58
85
59
86
Also, type inference can sometimes infer a too-specific type. Suppose we write:
60
87
88
+
{% tabs type-inference_6 %}
89
+
{% tab 'Scala 2 and 3' for=type-inference_6 %}
61
90
```scala
62
91
varobj=null
63
92
```
93
+
{% endtab %}
94
+
{% endtabs %}
64
95
65
96
We can't then go on and make this reassignment:
66
97
98
+
{% tabs type-inference_7 %}
99
+
{% tab 'Scala 2 and 3' for=type-inference_7 %}
67
100
```scala mdoc:fail
68
101
obj =newAnyRef
69
102
```
103
+
{% endtab %}
104
+
{% endtabs %}
70
105
71
106
It won't compile, because the type inferred for `obj` was `Null`. Since the only value of that type is `null`, it is impossible to assign a different value.
0 commit comments