Base.show() for custom types, print nothing when returning?

I have troubles understanding how show() works. I have a custom type that I would like to print something when called alone, but be silent when storing its value.

In R for example, print.customMethod is only called when customMethod() is called alone, not in the case of x <- customMethod()

Is that possible?

Here’s an example:

struct A
	text::Any
end

function A(; text)
    return A(text)
end

Base.show(io::IO, x::A) = println(io, x.text)


A(text="hello")  # Print
a = A(text="hello")  # I would like this to print nothing

I don’t think you can do this via show, as it cannot know the context. But why don’t you just do

a = A(text="hello");

(note ;).

1 Like

The REPL displays the value of an expression and both the expression rhs and assignment (lhs = rhs) has the “return value” rhs so from the REPL’s point of view there is no difference.

Didn’t know the semi-colon trick. Thanks!

I recall seeing it in the docs when I first learned Julia (v0.4), but I could not find it again with a quick search.

https://docs.julialang.org/en/v1/stdlib/REPL/#The-Julian-mode-1

A trailing semicolon on the line can be used as a flag to suppress showing the result.

with an example below it.

2 Likes

Thanks for pointing it out. I wonder if introducing the concept in the intro sections would be useful; new users may take some time to read up to this section.

But of course everything we more to the beginning crowds out something else, so this is a trade-off.