Unable to use add_agent!() function with keyword argument

Hi,

Just curious to find out if it is possible to use keyword argument with add_agent!() function.
When I tried adding a keyword argument, I got the following error : LoadError: MethodError: No Method matching CasAgent(::Int64, ::Typle{Int64, Int64}; TS = 2)

using Agents
mutable struct CasAgent <: AbstractAgent
    id::Int
    pos::Dims{2}
    TS::Int
end

space = GridSpace((10,10), periodic = false)
model = AgentBasedModel(
    CasAgent,
    space, 
    scheduler = random_activation
)

for pos in position(model)
    add_agent!(
        pos,
        model,
        TS = 2
    )
end

#Out > LoadError: MethodError: No Method matching CasAgent(::Int64, ::Typle{Int64, Int64}; TS = 2)

Of course removing the keyword would work fine. But I am wondering if there is a way to include a keyword.

for pos in position(model)
    add_agent!(
        pos,
        model,
        2
    )
end

#Out > AgentBasedModel with 100 agents of type CasAgent4

I also tried using the @kwdef from the base package but it didn’t work either

using Base::@kwdef
@kwdef mutable struct CasAgent <: AbstractAgent
    id::Int
    pos::Dims{2}
    TS::Int
end

for pos in position(model)
    add_agent!(
        pos,
        model,
        TS = 2
    )
end

#Out > LoadError: MethodError: No Method matching CasAgent(::Int64, ::Typle{Int64, Int64}; TS = 2)
@kwdef mutable struct CasAgent <: AbstractAgent
    id::Int
    pos::Dims{2}
    TS::Int = 0
end

You need to provide the default value for TS. Otherwise, the compiler wouldn’t know how to process CasAgent(1, (1, 1)).

Alternatively, according to Functions · The Julia Language you can define constructor with required keyword argument

mutable struct CasAgent <: AbstractAgent
    id::Int
    pos::Dims{2}
    TS::Int
end

CasAgent(id, pos; TS) = CasAgent(id, pos, TS)
3 Likes

Perfect answer!

We use this exact method in testing.

1 Like