Colin T Bowers
Colin T Bowers

Reputation: 18560

show method automatically running upon custom type construction

Every time I call a constructor for a custom-type, the show method for that type runs. I cannot work out why. Reproducible example follows:

I have a module:

module ctbTestModule1

import  Base.show

export  MyType1

type MyType1
    function MyType1()
        new()
    end
end

function show(io::IO, a::MyType1)
    println("hello world")
end

end

I open up a fresh julia session in the REPL and type:

using ctbTestModule1
z = MyType1()

The following prints to the console when I run the line z = MyType1():

hello world

How is the show method being called here? It certainly doesn't appear to be called in the inner constructor...

Upvotes: 0

Views: 58

Answers (1)

reschu
reschu

Reputation: 1105

The REPL (Read-evaluate-print loop) evaluates and prints every statement.

What you describe is the usual behavior.

Run z = 1 in your REPL and the printed output will be 1.

Likewise, your z is a MyType1 which is displayed as hello world.

If you want to suppress the output in the REPL finish your statement with a semicolon ;:

z = MyType1();

So, to answer your question: Yes, if you create an instance of a type in the REPL, the result is shown by calling the show() function of that type.

Upvotes: 2

Related Questions