Suppose you define a new composite type in Julia and a variable of that type:
type MyType
α::Int64
β::Vector{Float64}
γ::Float64
MyType(α::Int64, β::Vector{Float64}, γ::Float64) = new(α, β, γ)
end
mt = MyType(5, [1.2, 4.1, 2], 0.2)
Now if you are in REPL mode, you can simply check the value of mt
by typing mt
and pressing Enter:
mt
MyType(5,[1.2,4.1,2.0],0.2)
If I want to customize the way variables of MyType
are displayed, I can define a function and use it like customized_display(mt)
:
function customized_display(me::MyType)
println("MyType")
println("α:$(me.α), β:$(me.β), γ:$(me.γ)")
end
customized_display(mt)
MyType
α:5, β:[1.2,4.1,2.0], γ:0.2
But using another function for displaying values of mt
seems redundant. Which function do I need to extend such that by simply typing mt
, the customized display is shown?
You should define one of the following (they will both work and have the same effect):
Note: The answer by spencerlyon2 is no longer correct as of Julia 0.5 and later.
Given your type
If you want to customize the single-line display, add a method to
Base.show
like this:An example of single-line display being used:
By convention, this method should not include any newlines. This is so that it displays nicely when embedded in other objects, like arrays or matrices. Typically, it's preferred to output something that could be parsed and evaluated into an object equal to the one being shown, but this is not a hard rule.
If you want to customize the multi-line display, add a method to
Base.show
like this:Note that if you do not include this method, then the single-line display will be used. The multi-line display is used at the REPL when your object is shown on its own:
By convention, the multi-line display should not print any trailing new lines.