cincheo / jsweet

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

Default methods of j4ts classes #661

Open arenevier opened 3 years ago

arenevier commented 3 years ago

Hi,

When trying to implement a class belonging to j4ts, the default methods are not taken into account.

For example, the following code will fail to compile until I uncomment forEachRemaining.

import java.util.Iterator;
import java.util.function.Consumer;

public class MyIterator implements java.util.Iterator<Foo> {

    @Override
    public boolean hasNext() {
      return true;
    }

    @Override
    public Foo next() {
      return new Foo();
    }

    /*
    @Override
    public void forEachRemaining(Consumer<? super Foo> consumer) {
      while (hasNext()) {
        consumer.accept(next());
      }
    }
    */

    @Override
    public void remove() {
      // Do nothing
    }
}

Error messages is:

Class 'MyIterator' incorrectly implements interface 'Iterator'. [ERROR] Property 'forEachRemaining' is missing in type 'MyIterator' but required in type 'Iterator'.

Implementing an interface with default methods defined in my own package works fine.

renaudpawlak commented 3 years ago

Yes, that a known limitation of default methods with candies (including J4TS). The problem is that you need the source code of the candy in you your input in order to have JSweet correctly inject the methods in the implementing classes. In order to make it work without manual intervention, you need to use the extraInput option (https://github.com/cincheo/jsweet/blob/develop/transpiler/src/main/java/org/jsweet/JSweetCommandLineLauncher.java#L86) and add the J4TS source code root directory. It will be used by JSweet to generate the right code but no code from J4TS will be actually transpiled and generated. Same for other candies that would use default methods. Note that the option is available from the command line launcher, but I am not sure if it has been supported yet by the JSweet Maven plugin.

There would be other ways to overcome this issue, but it would require more work, so it is not part our any short terme plan...