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

Document that you should not overload promote_type directly #41386

Merged
merged 1 commit into from
Jun 29, 2021
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions base/promotion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,11 @@ Float16
julia> promote_type(Int8, UInt16)
UInt16
```

!!! warning "Don't overload this directly"
To overload promotion for your own types you should overload [`promote_rule`](@ref).
`promote_type` calls `promote_rule` internally to determine the type.
Overloading `promote_type` directly can cause ambiguity errors.
"""
function promote_type end

Expand Down
10 changes: 8 additions & 2 deletions doc/src/manual/conversion-and-promotion.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,15 @@ julia> promote_type(Int8, Int64)
Int64
```

Note that we do **not** overload `promote_type` directly: we overload `promote_rule` instead.
`promote_type` uses `promote_rule`, and adds the symmetry.
Overloading it directly can cause ambiguity errrors.
We overload `promote_rule` to define how things should be promoted, and we use `promote_type`
to query that.

Internally, `promote_type` is used inside of `promote` to determine what type argument values
should be converted to for promotion. It can, however, be useful in its own right. The curious
reader can read the code in [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl),
should be converted to for promotion. The curious reader can read the code in
[`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl),
which defines the complete promotion mechanism in about 35 lines.

### Case Study: Rational Promotions
Expand Down