lambda expression not expected here
Remi Forax
forax at univ-mlv.fr
Sat Jun 1 10:57:44 PDT 2013
On 06/01/2013 07:29 PM, Marc Petit-Huguenin wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA256
>
> Hi,
>
> The compilation of this code fails with a "lambda expression not expected
> here" error:
>
> int i = (f -> f + 1).applyAsInt(1);
>
> I am not sure to understand why this code is invalid as the following code
> compiles fine:
>
> int i = ((IntUnaryOperator)(f -> f + 1)).applyAsInt(1);
>
> If it is because the compiler cannot infer the type, then perhaps the error
> text could be improved.
>
> Thanks.
Hi Marc,
no the compiler can not infer the type, there is not enough information.
In your example,
int i = (f -> f + 1).applyAsInt(1);
One lambda can be converted to different functional interfaces,
by example,
interface IntToIntFun { int fun(int value); }
interface Operator<T> { T apply(T value); }
so the following statements are both valid:
IntToIntFun fun = f -> f + 1;
Operator<Integer> operator = f -> f + 1;
There is no way for the compiler to infer the type because they are more
than one possible choice.
Here, we pay the price that Java has no type for a function and uses the
more flexible and more java-like concept of function interface.
cheers,
Rémi
>
> - --
> Marc Petit-Huguenin
> Email: marc at petit-huguenin.org
> Blog: http://blog.marc.petit-huguenin.org
> Profile: http://www.linkedin.com/in/petithug
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.12 (GNU/Linux)
>
> iQIcBAEBCAAGBQJRqi97AAoJECnERZXWan7E+CsP/14IlYCyFkJsHuP8M1KAp38c
> ZGiCqyU2zkKGFdZuMNeslUD25NoLjLpBfNRlk1d4kWZzo+zFWKEnnE/wVJB49zRE
> bG4W9iS0ToktODLfDqawPHb4OAEurrqosA3BzUrAy/C7KoOISvvZwVIbXRO/zQi5
> I7/s3G5rb3aN84J6tYjVt0zIKhtBls45slpP+mN9gA8y/u+EZwtQgZc1WhAnKv73
> g5iBCvQK68m9bgj/sCs0W/Y60bRD6vpF3QR26z6mFFfT2Q7ykmSbIb0bF2GteFbr
> coRYM/Y6FtmAayPduSbTS3gDS9GuiHnnvJzwuM9Wgd/f/FkbDnhR8wXNdEoXh+ry
> klRteAHDzXgOrqHqOfDvWx9JgYqNi7bVw45H8AbsmJj20cdq0Amy8JWEh3iTD6Zy
> o6aR0iUpDeQ7Kg+IIn0lzccqBnh6+FKqZqsn5mIpNvPULeHTyu2B54AOUi52Kpez
> xDTiioUaRXLZynWpG2AghWTJqc2uZM7T81O+pPSZLPSaHVC7Dde+IU4KG+PvbuHx
> 84Rsl7h9wh4pnoxYFcC4WTCinBoF2KZ7MWqT9bUCQGI99FGUvqF4wN76t9tMytbC
> YztxzG8q3EHXThxH120dk3HhzyXUj5r4wqmHphH0r9kFN1N8u/Z+lELF4nJa/KCc
> BU9BWzp6qbKMt0PSJ7Dl
> =YAKJ
> -----END PGP SIGNATURE-----
>
More information about the lambda-dev
mailing list