views:

609

answers:

2

I'm designing an API (in Java) and expect to have users accessing the API from Matlab. The problem is that I want the API to provide a piece of functionality like:

javaApi.waitUntilPredicateIsTrue(Predicate<JavaObj> test);

My API (in the background) gets hold of instances of Java Obj (via some mechanism, e.g. polling). I want this API method to block until one of these instances, when passed to the Predicate evaluates to true. If I was calling this API from Java, I'd do:

javaApi.waitUntilPredicateIsTrue(new Predicate<JavaObj>() {
    public boolean evaluate(JavaObj jo) {
        return "READY".equals(jo.getState());
    }
});

You get the idea.

How can this be called from within Matlab? Can I use anonymous inner classes from Matlab? Can I declare a Matlab classdef which extends the interface Predicate (can this cope with the Java generic version)?

+1  A: 

Matlab has a much nicer solution than forcing users to create a whole class just to provide a single method. Take a look at their anonymous functions.

Note that anonymous functions in Matlab have odd scoping rules. Make sure you read the "Variables Used in the Expression" section of the linked help page. If you want more traditional lexical scoping, take a look at nested functions.

EDIT: I am assuming that you will be doing the polling from Matlab, not passing the predicate function to Java. Example:

function waitForPredicate(pred)
  while pred
  end
end

waitForPredicate(@()javaApi.isMyConditionMet());
Mr Fooz
Unfortunately not; I'm trying to make my API easier to use for the most common use-cases and from Matlab. Basically the API is used to access (Java) objects. However, the object may not be "ready" from the user's perspective. Rather than implement the polling logic themselves, I'd hoped to provide a simple waitUntilXIsReady mechanism. The problem with your suggestion is that there is no "isMyConditionMet" on the API. It is the Matlab end-user who needs to decide whether he's happy with it
oxbow_lakes
I should also say that the "polling logic" is more complicated than simply spinning on the "!conditionIsMet", sleeping for a bit inbetween (although you could do that). This is because a newer version of the object could be ready for you (it's pushed out via an event published to a multicast group). I really don't want my Matlab users messing about with the raw multicast!
oxbow_lakes
+2  A: 

That sounds like a tough question. I'm still running R2006b so this may have changed, but it looks like MATLAB will not translate function handles (incl. anonymous functions) and structures into Java objects. I don't know about MATLAB custom classes, since the syntax has changed. Strings, arrays, and cell arrays will translate properly. They don't comment at all on implementing interfaces. (:p :p :p BOO HISS)

edit: just found this page on Matlab Central, it talks about some undocumented interfaces.

Jason S