MATLAB: Directly accessing a method of a returned object shadows argument list

MATLABmatlab functionoop

Hi there. I have observed a weird issue:
I have a class that exposes a method which returns me an instance of another class.
classdef Factory
methods (Static)
function worker = getWorker(inputItems)
fprintf('No. of input arguments: %d\n', nargin);
worker = Worker();
end
end
end
classdef Worker
methods (Static)
function doSomething()
disp('Hello you');
end
end
end
When I call it like follows, everything works perfectly fine and all arguments in the getWorker method are where I'd expect them:
>> worker = Factory.getWorker(1); worker.doSomething()
No. of input arguments: 1
Hello you
However, when I use that returned instance directly, without assigning it to a variable. The arguments don't end up in the method, but rather the argument list is used as an index, for the returned objects (which could be an array … and hence non-numeric inputs mess everything up even more…):
>> Factory.getWorker(1).doSomething()
No. of input arguments: 0
Hello you
And my actual usecase would be the following, where my getWorker method does not have / need any input arguments, but then I get a warning:
>> Factory.getWorker().doSomething()
No. of input arguments: 0
Warning: A value of class "Worker" was indexed with no subscripts specified. Currently
the result of this operation is the indexed value itself, but in a future release, it
will be an error.
Hello you
Does anyone has an input, how I can enforce that the arguments end up in the right place, without assigning a real instance?
Used versions: Matlab 2017a and b on a Windows10 machine.

Best Answer

I remember reading somewhere (probably on Answers) that dot indexing the result of a method is not officially supported in matlab. Matlab does try to make it work but can't always succeed.
The problem is that
Factory.getWorker(x).doSomething
is ambiguous. Is it call getWorker with one argument, x, and use doSomething on the result returned by that method, or is it call getWorker with no argument, get the x element of the array returned by getWorker and use doSomething on that element?
Clearly, matlab choses the 2nd interpretation. I don't think there's any other way to remove the ambiguity other than creating assigning the result of getWorker to a variable. Maybe it could be made to work by calling subsref directly, but for static methods, I'm not even sure you can use subsref.