Skip to content

Kotlin Integration#

Requirements#

  • JDK 17 or later
  • Kotlin 2.0 or later

Installation#

<dependency>
  <groupId>org.odenix.mxpack</groupId>
  <artifactId>mxpack-kotlin</artifactId>
  <version>${mxpackVersion}</version>
</dependency>
dependencies {
  implementation("org.odenix.mxpack:mxpack-kotlin:${mxpackVersion}")
}
dependencies {
  implementation "org.odenix.mxpack:mxpack-kotlin:${mxpackVersion}"
}

Features#

Factory methods#

The Kotlin API offers factory methods that replace the Java API's factory methods. The factory methods are named after the Java interfaces they return. Instead of option handlers, they use named arguments with default values.

For example, to create a MessageReader, use the Kotlin factory method MessageReader() instead of the Java factory method MessageReader.of(). Occasionally, Kotlin factory method names differ from Java interface names. For example, to create a pooled BufferAllocator, use the Kotlin factory method PooledAllocator() instead of the Java factory method BufferAllocator.ofPooled().

var allocator = BufferAllocator.ofPooled(options -> options
    .maxByteBufferCapacity(1024 * 1024)
    .maxByteBufferPoolCapacity(1024 * 1024 * 32)
);
val allocator = PooledAllocator(
  maxByteBufferCapacity = 1024 * 1024,
  maxByteBufferPoolCapacity = 1024 * 1024 * 32
)

Extension methods#

Read unsigned integers#

fun read(reader: MessageReader) {
  val num1: UByte = reader.readUByteKotlin()
  val num2: UShort = reader.readUShortKotlin()
  var num3: UInt = reader.readUIntKotlin()
  var num4: ULong = reader.readULongKotlin()
}

Write unsigned integers#

fun write(writer: MessageWriter) {
  writer.write(UByte.MAX_VALUE)
  writer.write(UShort.MAX_VALUE)
  writer.write(UInt.MAX_VALUE)
  writer.write(ULong.MAX_VALUE)
}