Method call error: composite type

I have the following code,

abstract type A end
struct A1 <: A end
struct A2  <: A
    b1::Float64
    b2::Int64
end
function f(x, fonzi)
    if fonzi == A1() 
        return 2 * x
    elseif fonzi == A2()  # <-
        return fonzi.b1^fonzi.b2 * x 
    else
        return 0.0
    end
end

and run

f(1, A1())       # 2
f(1, A2(2.0, 2)) # errors

How may fonzi == A2() be changed so that f(1,A2(2.0, 2)) runs fine, instead of raising the following error:

ERROR: LoadError: MethodError: no method matching A2()
Closest candidates are:
  A2(::Float64, ::Int64) at /Users/Code/test.jl:4
  A2(::Any, ::Any) at /Users/Code/test.jl:4

Thanks in advance

You are comparing values when you mean to compare types.

fonzi == A2() asks whether fonzi has the same value as A2().

fonzi isa A2 asks whether fonzi is of type A2. That’s what you want.

3 Likes

Perfect! Thank you very much.