Skip to content

Java usage

Koding edited this page Jul 24, 2020 · 1 revision

โ˜• Java Usage

Although CraftLib is a Kotlin library, we aim to make it as usable as possible through pure Java. As such, we've written all our modules with Java usage in mind and some examples can be seen below.

It is recommended that you understand the basics of Kotlin to get the best experience, as you'll understand roughly how Kotlin code compiles.

Note: If you cannot find a Java equivalent in this document, it's recommended you look at the Java to Kotlin Interop page.

โฐ Suspend Functions

Many of our non-internal suspend functions will have a Future equivalent available. These wrap the coroutine into a Future object which can be used from pure Java.

These functions should begin with the suspend functions' full name and be suffixed with Future (e.g. readTag -> readTagFuture).

๐Ÿ”ง Using our utility

If there is no applicable functions provided by CraftLib, you can wrap the suspend function using our utility.

The asFuture function takes a lambda as an argument, providing a continuation variable. In this case, the NBTIO.read method is a suspend function, so we pass all the required arguments first and then the continuation variable as the last parameter.

This function will wrap the suspend function into a Future and return it.

import dev.zerite.craftlib.commons.util.CoroutineUtil;
import dev.zerite.craftlib.nbt.NBTIO;

public class Example {
    public static void main(String[] args) {
        CoroutineUtil.asFuture(continuation ->
            NBTIO.INSTANCE.read(stream, continuation)
        );
    }
}

๐Ÿ“ Extension Functions

Kotlin, unlike Java, includes the ability to create custom functions and parameters on any class. To use an extension in Java, simply run the appropriate function in the generated class.

Many of our classes have custom names for extensions, usually their class name followed by Util (e.g. ProtocolBuffer -> ProtocolBufferUtil).

If one of our classes doesn't use this format, it will instead be the class name followed by Kt (e.g. ProtocolBuffer -> ProtocolBufferKt).

When invoking these functions from Java, the first parameter will always be a reference to the instance we're performing this action on. After that, the following parameters will simply be the normal parameters for that method.

๐Ÿ‘‹ Introduction

Clone this wiki locally