tweag / inline-java

Haskell/Java interop via inline Java code in Haskell modules.
BSD 3-Clause "New" or "Revised" License
229 stars 15 forks source link

Inheritance #45

Open mitchellwrosen opened 7 years ago

mitchellwrosen commented 7 years ago

Hi, are there any plans to add support for Java inheritance? From scanning the docs, all I found was

upcast :: J a -> J (Class "java.lang.Object")

and

unsafeCast :: J a -> J b

However, it would be nice to have some sort of

upcast :: Extends a b => J b -> J a

instance Extends a (J (Class "java.lang.Object"))

instead.

Thanks!

mitchellwrosen commented 7 years ago

To this end, I've started work on a repo here: https://github.com/mitchellwrosen/java-apache-lucene/blob/master/jvm-extra/src/Language/Java/Extra.hs

However, the interface is inchoate and unstable, as there are many details in the Java type system (inheritance, generics, bounded generics in class/interface definitions e.g. <T extends Number>, wildcard/bounded generics in types, e.g. List<? super Integer>, and on and on, that are quite tricky to model!

I only mention my work here so anyone else interested in tackling this problem can get in touch to compare notes. Or, if there's prior work in this area, maybe I'm wasting my time. Either way, it's fun!

facundominguez commented 6 years ago

Another possible design is having a class

class Extends (ty1 :: JType) (ty2 :: JType) where

and functions

upcast :: Extends ty1 ty2 => J ty1 -> J ty2
downcast :: Extends ty1 ty2 => J ty2 -> IO (J ty1)
-- Doesn't check at runtime if the input reference has the expected type.
unsafeDowncast :: Extends ty1 ty2 => J ty2 -> J ty1

For a class instance like

class MyClass<A extends BClass & CInterface> extends MySuperClass<A> {
}

We could generate with Java reflection and template haskell:

instance (Extends ty ('Class "BClass"), Extends ty ('Iface "CInterface")) => Extends ('Class "MyClass" <> '[ ty ]) ('Class "MySuperClass" <> '[ ty ])
puffnfresh commented 4 years ago

I think Eta did a good job at this. It's very similar to what you've proposed @facundominguez.