Evo API Draft
  • Java
    • Intro
    • Imports
    • Constructing Objects
    • Properties
    • Type Annotations
    • Conversions
    • Explicit Conversions
    • Behaviors
    • Creating and Extending Types
    • Promises
  • mc-std
    • Intro
    • Commands
Powered by GitBook
On this page
  • Converters
  • To Java
  • From Java
  1. Java

Explicit Conversions

Create conversions for custom types

I'm only going to be showing the conversion API in TypeScript for this chapter. There will be a Java API for this, and you should totally use the Java API instead (for speed). However, I prefer to use TypeScript to show how the API will look, it's just nicer. The Java API will have very similar semantics.

Converters

In both directions, converters work the same way fundamentally.

  • Converters have a predicate and a transformer.

  • The predicate determines whether or not the converter will apply. For instance, it could check if the object is a String.

  • Then, the transformer will convert that object into the new datatype.

To Java

// Note that this conversion is built-in, don't implement it yourself.

Java.convert({
    type: 'toJava',
    predicate(object, javaType) {
        return Array.isArray(object) && javaType == ArrayList;
    },
    convert(object) {
        const arrayList = new ArrayList();
        for (const el of object) {
            arrayList.add(el);
        }
        return arrayList;
    }
});

From Java

// Note that this conversion is built-in, don't implement it yourself.

Java.convert({
    type: 'fromJava',
    predicate(object) {
        return object instanceof ArrayList;
    },
    convert(object) {
        const array = [];
        // See the chapter on "Behaviors" to understand
        // why we can iterate this so naturally.
        for (const el of object) {
            array.push(el);
        }
    }
});
PreviousConversionsNextBehaviors

Last updated 2 years ago