Overload `show` for array of custom types

Hello everyone, I’m trying to overload the Base.show method for arrays of custom types. I have an alternative solution that is to wrap the array into a new type, but I find it no sense.

Here is the thing

julia> struct MyType
       i::Int
       end

julia> MyType(3)
MyType(3)

julia> [MyType(2), MyType(3)]
2-element Array{MyType,1}:
 MyType(2)
 MyType(3)

Let’s print something for when creating instances of MyType

julia> Base.show(io::IO, x::MyType) = begin
       print(io, "Hello custom element")
       end

julia> MyType(2)
Hello custom element

Everything is fine until now, but when I try to overload the show function for the array…

julia> Base.show(io::IO, x::Array{MyType,1}) = begin
       print(io, "Hello array of custom elements")
       end

julia> [MyType(2), MyType(3)]
2-element Array{MyType,1}:
 Hello custom element
 Hello custom element

How can I solve that? Is it possible? (I think it is, everything can be solved AFAIK) Thanks!!

You can define

Base.show(io::IO, ::MIME"text/plain", ::Vector{MyType}) =
    print(io, "Hello array of custom elements")

and it will work. The problem seems to be that there is a 3-argument show defined for AbstractArrays which is called by display instead of your method. I think this is a known issue, but I can’t locate it ATM.

Also, on how you can find this out: use @edit and similar.

Cf. this discussion.

2 Likes