Does MATLAB have import statements in the scope of a class?
10 views (last 30 days)
Show older comments
Is it possible to put a single import statement somewhere in a classdef file such that it exposes the imported package to all methods in the class? It appears that placing such a statement anywhere outside a function definition is invalid syntax, but I am hoping that there may be some different way to have package imports in the global scope of a class.
As an example, consider the following (erroneous) implementation:
import some.long.package.name.myFn
classdef Foo
methods (Static)
function bar()
result = myFn() % executes myFn from the imported package
end
end
end
0 Comments
Answers (1)
Matt J
on 17 Feb 2022
Edited: Matt J
on 17 Feb 2022
The only thing that comes to mind is if you nest the actual implementations of all your methods (or at least those that will use the package) in a class-related function, like below.
classdef Foo
properties(Constant)
h=setupHandles;
end
methods
function varargout=method1(varargin)
[varargout{1:nargout}]=Foo.h.method1(varargin{:});
end
function varargout=method2(varargin)
[varargout{1:nargout}]=Foo.h.method2(varargin{:});
end
end
methods (Static)
function varargout=bar(varargin)
[varargout{1:nargout}]=Foo.h.bar(varargin{:});
end
end
end
function h=setupHandles(h) %class related function
import some.long.package.name
h.bar=@bar;
h.method1=@method1;
h.method2=@method2;
function result=bar()
result = myFn();
end
function method1()
...
end
function method2()
...
end
end
1 Comment
Steven Lord
on 17 Feb 2022
Another approach is to define class-related functions whose names match the last part of the fully qualified name and that call the package function via its fully qualified name. I ran the following in release R2021a (what I had open at the moment) and it passed.
classdef testForPlus < matlab.unittest.TestCase
methods(Test)
function tooManyOutputs(testcase)
testcase.verifyThat(@() 1+1, ...
Throws('MATLAB:needMoreRhsOutputs', 'WhenNargoutIs', 2))
% Depending on your release this may throw an error with a
% different ID
end
end
end
function y = Throws(varargin)
y = matlab.unittest.constraints.Throws(varargin{:});
end
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!