Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using of AdditionalBound in cast expressions

Can the AdditionalBound described in JLS8 cast expression be used for casting anything except that a lambda expression or a method reference?

It is said, that it could be:

( ReferenceType {AdditionalBound} ) UnaryExpressionNotPlusMinus 

and that:

The target type for the casting context (§5.5) introduced by the cast expression is (...) the intersection type denoted by the ReferenceType and AdditionalBound terms appearing in the cast operator.

But I'm failed to find a workable example with a non-lambda or a non-method-reference example, say something like:

 X x = (I1&I2) some_UnaryExpressionNotPlusMinus

UPD:

In particular, it allows something like

X x = (I1&I2) ~ UnaryExpression, where ~ is unary operator.

I have no idea what X, I1, I2 and UnaryExpression should be in this case.

UPD-2: Thanks to @Jimmy T., he has shown the workable example of

Object x = (Number&Serializable)~0;.

But it would be nice to see a non-redundant example, where such casting has sense.

UPD-3: According to the fact that all these expressions above are compiled, but all of them don't have any sense:

    Object l1 = (Collection & Iterable) new ArrayList<>();
    List l2 = (ByteList & Iterable) new ArrayList<>();
    Collection l3 = (List & Iterable) new ArrayList<>();

I can't imagine a case where such casting would be sensible.

like image 895
Andremoniy Avatar asked Jan 10 '16 14:01

Andremoniy


Video Answer


1 Answers

This can be compiled:

Object x = (Number&Serializable)~0;

This also can be compiled:

void method()
{
    method2((Number&Serializable)~0);
}

<T extends Number&Serializable> void method2(T x)
{

}

An example where the cast is actually needed:

void method(Object o)
{
  method2((List&AutoCloseable)o);
}

<T extends List&AutoCloseable> void method2(T v)
{

}
like image 70
Jimmy T. Avatar answered Sep 28 '22 17:09

Jimmy T.