Skip to content

Commit

Permalink
doc: in constructors, note the correspondence with callable objects (J…
Browse files Browse the repository at this point in the history
  • Loading branch information
nsajko committed Feb 12, 2024
1 parent 987d6f3 commit d6396f1
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions doc/src/manual/constructors.md
Original file line number Diff line number Diff line change
Expand Up @@ -575,3 +575,53 @@ This constructor will be invoked by the syntax `SummedArray(a)`. The syntax `new
specifying parameters for the type to be constructed, i.e. this call will return a `SummedArray{T,S}`.
`new{T,S}` can be used in any constructor definition, but for convenience the parameters
to `new{}` are automatically derived from the type being constructed when possible.

## Constructors are just callable objects

An object of any type may be [made callable](@ref "Function-like objects") by defining a
method. This includes types, i.e., objects of type [`Type`](@ref); and constructors may,
in fact, be viewed as just callable type objects. For example, there are many methods
defined on `Bool` and various supertypes of it:

```julia-repl
julia> methods(Bool)
# 10 methods for type constructor:
[1] Bool(x::BigFloat)
@ Base.MPFR mpfr.jl:393
[2] Bool(x::Float16)
@ Base float.jl:338
[3] Bool(x::Rational)
@ Base rational.jl:138
[4] Bool(x::Real)
@ Base float.jl:233
[5] (dt::Type{<:Integer})(ip::Sockets.IPAddr)
@ Sockets ~/tmp/jl/jl/julia-nightly-assert/share/julia/stdlib/v1.11/Sockets/src/IPAddr.jl:11
[6] (::Type{T})(x::Enum{T2}) where {T<:Integer, T2<:Integer}
@ Base.Enums Enums.jl:19
[7] (::Type{T})(z::Complex) where T<:Real
@ Base complex.jl:44
[8] (::Type{T})(x::Base.TwicePrecision) where T<:Number
@ Base twiceprecision.jl:265
[9] (::Type{T})(x::T) where T<:Number
@ boot.jl:894
[10] (::Type{T})(x::AbstractChar) where T<:Union{AbstractChar, Number}
@ char.jl:50
```

The usual constructor syntax is exactly equivalent to the function-like object
syntax, so trying to define a method with each syntax will cause the first method
to be overwritten by the next one:

```jldoctest
julia> struct S
f::Int
end
julia> S() = S(7)
S
julia> (::Type{S})() = S(8) # overwrites the previous constructor method
julia> S()
S(8)
```

0 comments on commit d6396f1

Please sign in to comment.