Welcome to the Julia forum
I personally feel the Method not Matching
error is very informative, since it even tells you which (hopefully closest) alternatives exist, so that you can fix the error (and indeed provide two arguments).
For me that usually helps more than a println, (or “manual own error”), since it has these hints included.
However, you could get to your version for example like
function cone_volume(r=nothing, h=nothing)
(isnothing(r) || isnothing(h)) && error("The function cone_volume requires two arguments, radius and height")
return π * r^2 * h/3
end
Here, I went for error
in stead of your print
, since that print would cause the function to return nothing
, which would anyways make the next computations you would do with the result of the function to very probably error.
Benny’s solution also covers the case for more than 2 arguments, which this approach does not.
So you could do this, but I do not feel that is the Julia way, the Julia way – in my oppinion – is to see the Method Error.
For the type check, I am not so sure what you would like to check, but if you want both to be of same type you could do
cone_volume(r::T, h::T) where T = π*r^2*h/3
then you get
one_volume(1, 1.0)
ERROR: MethodError: no method matching cone_volume(::Int64, ::Float64)
Closest candidates are:
cone_volume(::T, ::T) where T
@ Main REPL[1]:1
which might be something nice, but note that the original function does conversions if they exist, i.e. here it would convert the integer to a float and then return a float result (with the pi it would anyways do that also for 2 ints for sure).
So, again, I think for this function the T
is not so useful, but in general it might be nice to now this exists, and you can even restrict the T
by writing e.g. where {T <: Real}
or so.