Skip to content

FAQ: tweak answer about this.type #3103

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

Merged
merged 1 commit into from
Nov 12, 2024
Merged
Changes from all commits
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
18 changes: 10 additions & 8 deletions _overviews/FAQ/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,14 +292,16 @@ For more details, see the Scala Style Guide, [here](https://docs.scala-lang.org/

### How can a method in a superclass return a value of the “current” type?

First, note that using `this.type` won't work. People often try that,
but `this.type` means "the singleton type of this instance", a
different and too-specific meaning. Only `this` itself has the
type `this.type`; other instances do not.

What does work? Possible solutions include F-bounded polymorphism
_(familiar to Java programmers)_, type members,
and the [typeclass pattern](http://tpolecat.github.io/2013/10/12/typeclass.html).
Using `this.type` will only work if you are returning `this` itself.
`this.type` means "the singleton type of this instance". Only `this`
itself has the type `this.type`; other instances of the same class do
not.

What does work for returning other values of the same type?

Possible solutions include F-bounded polymorphism _(familiar to Java
programmers)_, type members, and the [typeclass
pattern](http://tpolecat.github.io/2013/10/12/typeclass.html).

This [blog post](http://tpolecat.github.io/2015/04/29/f-bounds.html)
argues against F-bounds and in favor of typeclasses;
Expand Down