#2628 How to use Java constucts?

isomorph Wed 16 Aug 2017

I do want to use some Java stuff in the fantom code. The documentation says something about using Java-apis, so i want to change this code:

  • Int[]? list := [,] to something like this:
  • Int[]? list := new ArrayList<Int>() by adding "using [java] java.util::ArrayList". (<- seems to work - no errors, but java.util.ArrayList wouldn't throw errors too) The change doesn't work of course, but how can i create objects und use them from the Java-api?

(yes, i know that the list fantom is using is an arraylist, but i just want to know how i can use Java stuff in the fantom code with this example)

SlimerDude Wed 16 Aug 2017

You're almost there - the answer is a lot simpler than you think!

using [java] java.util::ArrayList  // (this was correct!)

...

list := ArrayList()
list.add("Hello!")

echo( list[0]     )  // --> "Hello!"
echo( list.get(0) )  // --> "Hello!"
echo( list.typeof )  // --> [java]java.util::ArrayList

Note there are no user generics in Fantom, so in the case of ArrayList, the values are always of type Obj?.

isomorph Wed 16 Aug 2017

Should have told that i want to declare this variable direct in a class not in a method - i realized now there is a difference. How you show it (and i already tried) does not work outside a method. It says then: "Type inference not supported for fields" (haven't recognized this earlier, course i prefer to declare the type...). The fantom code

  • Int[]? list := [,]

works perfectly fine there. So i think i have to declare the data type course the same error appears when i do this:

  • list := [,]

However this is the code i searched and found with your help:

  • Obj? list := ArrayList()

Thank you!

SlimerDude Wed 16 Aug 2017

Try this instead:

ArrayList list := ArrayList()

If you declare a field to be of type Obj? then the compiler will just treat it as such, which (usually) isn't very useful!

isomorph Mon 21 Aug 2017

Yeah of course - just haven't thought that it recognize this type.

Do you know why it's a bit slower when i use the Java-ArrayList manually like this than using the fantom code (the fantom code will use an Java-ArrayList too - so what's the difference)?

SlimerDude Tue 22 Aug 2017

I am not aware that there is, or should be, a speed difference between using JavaFFI and not. I'll have to defer to someone more knowledgeable.

brian Wed 23 Aug 2017

Do you know why it's a bit slower when i use the Java-ArrayList manually like this than using the fantom code

Fantom does not use ArrayList, it has its own low level implementation of sys::List based on a Java array. In general unless you are trying to interop with Java code, its better to prefer Fantom's built-in APIs

Login or Signup to reply.