X .-= 2 for scalar x fails

julia> x = 1
1

julia> x .-= 2
ERROR: MethodError: no method matching copyto!(::Int64, ::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{0},Tuple{},typeof(-),Tuple{Int64,Int64}})

Is this intentional? Since scalars are iterable, why broadcast should fail here?

Yes, this is intentional. Scalars are immutable types, not containers. Implementing the broadcast interface does not guarantee that this type of assignment would work. If it did, it wouldn’t be possible for scalars to implement it.

The behavior you are looking for is implemented by a 1-element array, so if you really needed this (I don’t know your use case, but I’m guessing you’d probably be better off just doing -=) you could create one.

3 Likes