How to create a function that uses an object attribute if it exists

Hey everyone, I believe what I am trying to do is pretty simple, but I couldn’t figure it out by myself, and what I read from the documentation wasn’t very helpful. Also, I did search in the forum but couldn’t find exactly what I am looking for, so I decided to open a new topic.

The thing is: I have an object which can have or not a certain attribute (an array of arrays, by the way) depending on the input.
Then, I want to create a function that will have some of the object’s attributes as arguments, including this one that may or may not exist. How can I do it?

Handling the existence or not of such argument inside the function is not a problem to me (I thought about creating a flag and passing it as a argument too, but any advice to improve is welcome), the trouble I’m having is really how to create the function.

Any help will be welcome! Thanks in advance!

Depending on what you mean by “attribute”, the functions hasproperty or hasfield might be of help.

1 Like

It isn’t clear what you mean by attribute.
That isn’t a name of a thing in julia.
I am gettuing maybe you mean a type of a field?

2 ways to do this.
The direct way is to have that field types as Union{Array{Array{Float64}, Nothing}
and then set it to nothing to indicated that it isn’t present.
Which you cna then dispatch on, if you put it into a types argument.

However, needing to do this, is a bit of a code smell.
You might be better off having two differnet types, one with this field and one without.


Though maybe i am misunderstanding the question.
And you are saying you already have two types,
and you want to workout which you have.
In which case you can write multiple methods that dispatch on the type to know

1 Like

Thanks very much for your answers! As I don’t have formal education in Julia, some of the terms you used were unfamiliar to me, so I went searching for it and ended up understanding my problem (it turns out my struct implementation was wrong from the beginning). Using Union{Array{Float64},Nothing} is exactly what I was looking for.

Thank you very much again! :wink: