How to overload .=?

I would like to overload broadcasted assignment (.=). What is the correct way to do this, while still using .=? Is this possible?

1 Like

.= is syntactic sugar for a call to broadcast!, so you could overload broadcast!.

Hard to say more without knowing what you are trying to accomplish. e.g. give an example of the code you would like to write using .=, and what you would want it to do.

1 Like

Not quite. .= and broadcast! lower to the same thing. To overload .= you need to hook into the custom broadcasting machinery.


Thanks for the answers, and indeed hooking into the custom broadcasting machinery would solve this (haven’t tried it yet). @stevengj : below a simple example of what we/I are trying to do, basically we want to update interdependent fields of a struct, after initialization.

@with_kw struct Pars
           b::Vector{Float64} = a .+ 0.5

pars = Pars(a=[0.1,0.5,0.8])

pars.a .= [2.0,3.0,4.0]

expected with overload of .= : b: Array{Float64}((3,)) [2.5, 3.5, 4.5]

Ah, that’s not possible yet. It’ll only become possible with make broadcasting into getproperty extensible by simeonschaub · Pull Request #39473 · JuliaLang/julia · GitHub.

If pars.b must always mirror pars.a, you could use a “computed” getproperty overload instead so it’s only created/computed on demand.

1 Like