Question on exception transparency
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Tue Aug 10 02:56:28 PDT 2010
Hi
your code contains an example of circular inference (as the unknown type
of a lambda parameter is used in order to perform method resolution
inside the lambda body); there are three ways to solve this:
1) You can type in the target type explicitly (as you've done); this
lead to the rather verbose:
foreach(..., Block<String, BlockExecutionException> #(x) {execute(x)});
2) You can secify explicit type-parameters for the 'foreach' method:
<String, BlockExecutionException>foreach(..., #(x) {execute(x)});
3) You can specify the type of the lambda parameter:
foreach(..., #(String x) {execute(x)});
The alternative (3) looks the less verbose.
[Note: in this particular case I think there's room for type-inference
to swallow the circularity, as there's just one 'execute()' method -
however, in the general case, it is not safe to do so, as there could be
multiple overloaded version of the called method, or, the thrown types
of the called method could be generic in a 'throws' type-variable - in
such cases the 'real' type of the lambda parameter can significantly
alter the way in which lambda thrown types are inferred - as such, the
compiler must play the conservative card and infer Exception].
Maurizio
On 10/08/10 07:16, Rizal Anwar 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 ?
>
> Best regards,
> Anwar Rizal.
>
>
>
>
>
More information about the lambda-dev
mailing list