Question on exception transparency
Neal Gafter
neal at gafter.com
Mon Aug 9 23:45:38 PDT 2010
On Mon, Aug 9, 2010 at 11:16 PM, Rizal Anwar <anrizal05 at yahoo.fr> wrote:
> Hi,
>
> I played around with the prototype, and I have a question on exception
> transparency, especially in type inference.
>
> I have the following interface:
>
>
> public interface Block<T, throws E> {
> void run(T param) throws E;
> }
>
> and the following code (assuming ListUtil.foreach is a method accepting a
> list
> and a Block).
>
> public static void main(String args[]) {
> List<String> myList = Arrays.<String>asList("A", "B", "K");
> try {
> ListUtil.foreach(
> myList,
> Block<String, BlockExecutionException> #(x) {execute(x)});
> ////////////////////////////////////////////////////////////
>
> }
> catch (BlockExecutionException e) {
> e.printStackTrace();
> }
> }
>
> private static void execute(String x) throws BlockExecutionException {
> System.out.println("Execute" + x);
> }
> }
>
> I wonder whether there is a way not to specify the target Block<String,
> BlockExecutionException> in the closure I use in the above code ?
> Isn't is possible to infer the type ?
>
We know it is possible, as BGGA does just that. However, project lambda
cannot use the BGGA approach, as it does not resolve names in the enclosing
scope, but instead resolves names in the scope of the SAM being
constructed. In your example, project lambda requires the target SAM type
in order to determine which method "execute" is being invoked (it might be a
method inherited from the SAM). It needs to know what method that is to
know what exceptions it throws. It needs to know the thrown exception types
to determine the target SAM. This catch-22 is broken in project lambda by
requiring the SAM type be made explicit when the lambda is a parameter to a
method invocation.
There are two simple ways to address this:
(1) Leave things as they are, requiring an explicit target type when lambdas
are passed as parameters. In that case lambda expressions can best be though
of as a slightly shorter syntax for anonymous inner classes that otherwise
suffer all the same problems.
(2) Simplify lambda scoping to be lexical, enabling the target type to be
inferred as in BGGA
It is imaginable that some not-yet-discovered and probably complex, subtle,
and clever technique would enable both type inference and project lambda's
problematic scoping. No such scheme has yet been proposed.
More information about the lambda-dev
mailing list