cincheo / jsweet

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

Canonical way to do typed HashMap<String, ?> without j4ts #206

Open KramerTech opened 7 years ago

KramerTech commented 7 years ago

Basically, I'm just looking for a way to type the value of a javascript object like

public class TypedObject<T> extends jsweet.lang.Object

such that the methods (only the Java side, of course) enforce typing:

public T $get(String key) public $set(String key, T value)

Maybe I'm overlooking something really simple here, but I've searched high and low and haven't found a way to do this that's not nasty.

And just for additional info, my use case is: private static Object keyListeners = new Object(); And I want to be able to do something like: Array<Function> callbacks = keyListeners.$get(key); instead of Array<Function> callbacks = (Array<Function>) keyListeners.$get(key);

renaudpawlak commented 7 years ago

Ok. I think I will manage to improve the $get method in version 2 (WIP). Not so sure however, so I will try to keep your usecase in mind. With version 1, the $get method returns an object.

You could subclass the jsweet.lang.Object class... But personally I'd prefer the cast for now because it looks horrible to create a subclass for it.

class TypedObject<T> extends jsweet.lang.Object {
    @SuppressWarnings("unchecked")
    public T $get(String key) {
        return (T)super.$get(key);
    }
}
KramerTech commented 7 years ago

Ok, well it's a relief to know it's not possible yet. I was just sure I was missing something.

I agree the subtyping is nasty. And the javascript it creates isn't nearly as clean either. Casting's not a big burden, but I figured since part of the reason to use Java is the strong typing, there'd be a way to do it.

I look forward to v2, keep up the great work!