cincheo / jsweet

A Java to JavaScript transpiler.
http://www.jsweet.org
Other
1.46k stars 158 forks source link

window.setTimeout() function #40

Closed renaudpawlak closed 8 years ago

renaudpawlak commented 8 years ago

[I report here a question from Satguru for sharing with the community]

Not sure how to use the window.setTimeout() function.

Jsweet defines it as

native public double setTimeout(Object handler, Object timeout, Object... args);

This does not allow me to pass a java function to it

For example window.setTimout(this::aMethod,0,"abc");

gives following error The target type of this expression must be a functional interface

renaudpawlak commented 8 years ago

There is a Function object in jsweet.lang (part of the core JavaScript API). You can cast a well-typed lambda to a Function object using jsweet.util.Globals.function. For example:

import static jsweet.util.Globals.function;

window.setTimout(function(this::aMethod),0,"abc");

Most functions in API are well-typed, but some remain as function objects... so it is good to know this trick.

ssatguru commented 8 years ago

That worked and that definitely is good trick to know :)

Much better than the following hack I was going to use

BiConsumer<BiConsumer,Double> setTimeout = (BiConsumer<BiConsumer, Double>) window.$get("setTimeout"); 
setTimeout.accept(this::aMethod,0d);
renaudpawlak commented 8 years ago

Indeed, your trick works too :) Note that the core API is currently improving typing, so that such tricks will be less and less required in the future.