Conversions
Conversions in the Java API
We'll be focusing on these primitive datatypes:
String
Number
Boolean
Undefined
Null
As well as these two complex datatypes:
List
Map
In this chapter, we'll only be detailing implicit conversions. In the next chapter, we'll define a
To Java
When you call a method on a Java class, that method defines a datatype for the method. Take this one:
static int Bukkit.broadcastMessage(String message)
.
Now, let's say in JS: Bukkit.broadcastMessage("Hello World!")
. The important thing to note is that "Hello World"
is a JS string. It has to be converted to a Java string when you call the method.
Note that Evo handles both the primitives (i.e. "Hello"
) and the boxed class (i.e. new String("Hello")
. This applies to java too (int
vs Integer
.)
Here are the primitive conversions that Evo handles for you.
string
String
number
byte, short, int, long, float, double
bool
bool
null
null
undefined
null
For lists and objects, we provide conversions for a few popular Java classes (note that the inner elements will also be converted.)
T[]
ArrayList<T>, LinkedList<T>
Record<string, T>
HashMap<String, T>
With implicit conversions, you cannot convert maps with different value-types. For instance:
There's also two additional conversions involving interfaces.
(a: A, b: B...) -> T
(any Java interface with one method.)
Record<String, InterfaceMethod>
(any Java interface)
As one as one final conversion for Java CompleteableFuture
s.
CompleteableFuture<T>
Promise<T, any>
To TypeScript
Converting to TypeScript is much more limited than the other way around, because it's unclear what type should be converted back to (extracting that information from the runtime is very difficult.) So instead, each Java return type is converted to one, and only one JS type.
String
string
byte, short, int, long, float, double
number
bool
bool
null
null
ArrayList<T>, LinkedList<T>
T[]
HashMap<String, T>
Record<string, T>
Implicit conversions will mostly be handled for you, and likely optimized into Evo itself.
If you want to create your own conversions, check the next chapter.
Avoidance
What if I want to get the ArrayList<T>
directly, and not have it be converted to a T[]
? This use-case is supported by calling the .native
method on any Java method.
Explicit Conversions
You can explicitly convert from and to Java using the toJava
and fromJava
methods. With toJava
, you have to specify a type to convert to.
Last updated