Error printing custom types

If we define a new show method for a custom class and then create a variable with said class, Juno will keep printing the variable to the REPL. Here is a MWE:

import Base.show
mutable struct foo
    bar
end
function show(io::IO, a::foo)
    print(a.bar)
    return
end
t = foo(1)

If we run this, it will print 11 to the REPL (which is already wrong, since it’s showing t twice). Furthermore, all following REPL prompts will show julia>1.

This does not happen if we execute the code directly from the REPL.

That’s happening because your definition of show is wrong. You’re printing to stdout instead of io, so whenever show is called you’ll see a 1 pop up in the REPL. When Juno shows your variable in the Workspace show is called, just like when displaying a result in the REPL – you’ll end up seeing 11.

Basically, your code works in the REPL only by accident, because usually io == stdout in that case.

1 Like