Skip to content
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

FAQ for type inference #2924

Merged
merged 3 commits into from
Nov 28, 2023
Merged
Changes from 1 commit
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
23 changes: 13 additions & 10 deletions _overviews/FAQ/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,18 +196,21 @@ be written using the `_` syntax.

See also [SLS 6.23.2](https://scala-lang.org/files/archive/spec/2.13/06-expressions.html#placeholder-syntax-for-anonymous-functions).

### Why doesn't my dotted expression work?
### Why couldn't Scala infer the correct type in my code?

When methods have type parameters, the compiler makes a best effort to infer them
if they are not supplied explicitly in a method application.
Type parameter inference is improved in Scala 3.
It is difficult to generalize about type inference, because various features of the language
affect how your code is construed. There may be several ways to rewrite your code to make
the types fall out naturally.

```
scala> List("ab").toSet.head.head
^
error: value head is not a member of type parameter B
```
For more context, see [this section of the tour](https://docs.scala-lang.org/tour/multiple-parameter-lists.html#drive-type-inference).
The most straightforward workaround is to supply explicit types in your code.

That may involve specifying an explicit type to a definition, or a type argument to a method.

Type inference is greatly improved in Scala 3. If Scala 2 doesn't compile your code, it's worth trying with Scala 3.

Sometimes, using multiple parameter lists helps inference, as explained in [this section of the language tour](https://docs.scala-lang.org/tour/multiple-parameter-lists.html#drive-type-inference).

For paradigmatic questions about type inference involving `toSet`, see the discussions on [this ticket](https://github.com/scala/bug/issues/7743) and a related [Q&A](https://stackoverflow.com/questions/5544536/in-scala-2-type-inference-fails-on-set-made-with-toset).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overall LGTM but I ask for one change: s/paradigmatic/common/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok I accept pitching it to the commons


### Can I chain or nest implicit conversions?

Expand Down
Loading