Skip to content

Commit

Permalink
Document that you should not overload promote_type directly (JuliaLan…
Browse files Browse the repository at this point in the history
  • Loading branch information
oxinabox authored and johanmon committed Jul 5, 2021
1 parent c37baaf commit 7822949
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
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

0 comments on commit 7822949

Please sign in to comment.