How to declare (and pass) Julia function parameters when the parameter could be one of two types

Viewed 90

My goal is to pass an IOStream variable to a Julia function (if I want to write to an open file), or nothing (or possibly something else that would be considered an empty or null value). The reason is that I might call this function numerous times and would like to keep the file handle open regardless of how many times I enter the function. If the intent is not to write to the file, I would simply pass nothing indicating to the function not to attempt writing to a file.

I have tried declaring as:

function f(x, y, f)

and as:

function f(x, y, f::IOStream)

and as:

function f(x, y, f::Any)

while passing in a variable set to either nothing or an IOStream resulting from a

open("filename.txt", "a")

statement. In all cases, I get an error of some sort. Is there some other way to achieve my goal, or should I be using a different type of function declaration/call?

1 Answers

You should not have the same name for function and parameter. Anyway there are two approaches - either you use type Union or multiple dispatch.

Hence your code can be either:

function f(x, y, fs::Union{IOStream,Nothing}=nothing)
    #code goes here
end

or you can do:

function f(x, y, fs::IOStream)
    #code goes here
end
function f(x, y, fs::Nothing)
    #code goes here
end

Instead of the second function you could as well just do:

function f(x, y)
    #code goes here
end
Related