Overloading of getfield
and setfield!
is coming in 1.0, which will allow you to do things like
getfield(k::koly, f::Symbol) = (f == :V) && (return V) # this is not a great way of doing this but it works
k = koly(1, 1.0)
k.V(x)
However, this is somewhat in violation of the spirit of multiple dispatch. The recommended procedure would be to instead define
V(k::koly, x) = k.x + x^2 # this is just an example, in case you'd want V to involve koly somehow
If you’re coming from more traditional object oriented languages, this may at first seem like a bizarre anti-pattern. Once you get a bit used to it, however, you will probably learn to love and embrace it. There is very rarely any reason for objects to “own” functions in this way, it is simply an historical artifact of C++. Your example demonstrates that quite well (even though I’m sure it was simplified for demonstration purposes): if you just want to square a float, there is no reason for the function doing this to have any special relation to koly
. koly
is a type, not a namespace. If you are looking for a namespace, module
serves that purpose.
I come from C++ originally, but now I would find it very painful to go back to the traditional object-oriented way of doing things. See also this.
Despite this, as @favba pointed out, there is nothing stopping you from storing function references as properties of structs, however I’d urge you to contemplate whether this is really what you want to do.
By the way, I may have been a little confused by exactly what you were looking to do, perhaps it was
V(x::Real) = x^2
V(k::koly) = V(k.x)