Redefine the show function

function, b::BasisSetRep)
    print(io, "BasisSetRep($(b.h)) with dimension $(dimension(b)) and $(nnz( stored entries:")
    show(io, MIME"text/plain"(),

This is some people’s code.

I am confused with the name of this function. As far as I know, ‘show’ is a built-in function of julia in the Base package, right? Then how can you redefine a show function? Why not a new function with a new name?

Because you want to change how a custom structure is shown in the REPL, and that is what does:

julia> struct A

julia> function, a::A)
           println("My A type has a field x with value: $(a.x)")

julia> A(2)
My A type has a field x with value: 2

ps: This is not a redefinition of, is adding a new method for that function, for the new type A.


See Methods · The Julia Language

1 Like

Adding onto @lmiq’s solid response, the function is what Julia uses under the hood to know how to pretty-print something on screen, often called in response to a REPL prompt. The first argument tells Julia where to send the stream of resultant characters, and the second argument is the thing you want to see printed.

Julia uses a multiple dispatch system where you can write multiple different methods for a function, each with different argument types, and the compiler will select the appropriate method based on the arguments being used. You can see here in the Julia source where the show function is defined that there are tons of different methods based on different second argument types.

The code you quoted at the top of this page just implements a show method for a new type BasisSetRep and adds it to the existing method table.

1 Like