cincheo / jsweet

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

Optional support #613

Closed crummy closed 3 years ago

crummy commented 4 years ago

I like Java 8's optionals:

class Foo {
  private String inner;
  public Optional<String> getInner() {
    return Optional.ofNullable(inner);
  }
}

Jsweet 2 doesn't seem to support this. Ideally these types would be outputted to a nullable type in the TS definition: https://www.typescriptlang.org/docs/handbook/advanced-types.html#nullable-types

lgrignon commented 4 years ago

Hello @crummy Nice idea indeed!

IMHO transpiling to nullable type should be an option because TypeScript's strict mode for nullability is an option (since TS3 I think).

Maybe a first step could be just to transpile to the underlying type. So Optional => X => mapped type of X

I know that you already gave it a try. Did you notice this line https://github.com/cincheo/jsweet/blob/develop/transpiler/src/main/java/org/jsweet/transpiler/extension/RemoveJavaDependenciesAdapter.java#L171 which does something similar? It checks that given type is a Throwable, and if so, prints type Error.

Our case is a bit more difficult but this could be a good start for you if you want to try again :)

crummy commented 4 years ago

I think the code you linked checks the class, and verifies if any of its ancestors is Throwable, and returns "Error" if so. But that's not really what I'm looking to do - I want to check for class Optional.class, and if so, inspect the generic inside the optional.

I tried it out here, but my tests consistently fail with:

ERROR: [ts] Cannot find name 'Optional'. Did you mean 'Optionals'? at src/test/java/source/optional/Optionals.java(6)

https://github.com/cincheo/jsweet/compare/develop...crummy:develop

lgrignon commented 3 years ago

Optional support has been integrated in latest 2.x & 3.x