https://github.com/kilemonn/java-union
A simple union implementation in Java/Kotlin.
https://github.com/kilemonn/java-union
java-library kotlin library reflection union
Last synced: about 1 month ago
JSON representation
A simple union implementation in Java/Kotlin.
- Host: GitHub
- URL: https://github.com/kilemonn/java-union
- Owner: Kilemonn
- License: apache-2.0
- Created: 2025-08-07T13:49:51.000Z (2 months ago)
- Default Branch: main
- Last Pushed: 2025-08-18T14:15:36.000Z (about 2 months ago)
- Last Synced: 2025-08-18T16:14:57.674Z (about 2 months ago)
- Topics: java-library, kotlin, library, reflection, union
- Language: Kotlin
- Homepage:
- Size: 95.7 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# java-union
[](https://github.com/Kilemonn/java-union/actions/workflows/gradle.yml) [](https://github.com/Kilemonn/java-union/actions/workflows/gradle.yml)
A simple union implementation in Kotlin allowing you to initialise the union instance with a specific object
and re-interpret the internal byte array as different types.
The byte array cannot be interpreted as a type that is larger than the buffer.## Quick Start
This can be included by making sure that you have [JitPack](https://jitpack.io/) setup as a dependency repository within your project.
You can refer to the hosted versions of this library at [java-union](https://jitpack.io/#Kilemonn/java-union).```groovy
implementation("com.github.Kilemonn:union:0.1.0")
```### Example
The below example in `Kotlin` stores a `Char` in the `Union` and reads its value out as a `Short`.
```kotlin
val char = 'c'
val union = Union(char)// The union's size is 2 since char's are 2 bytes in the JVM
assertEquals(2, union.size)// Will have value 99 because of 'c' having the ASCII value of 99
val asShort = union.asType(Short::class.java)
assertEquals(99, asShort)// This will return null, since the size of an int is 4 bytes, which is larger than the current
// internal Union buffer (`union.size`)
val asInt = union.asType(Int::class.java)
assertNull(asInt)
```### Limitations
- Currently only primitive and object primitive types will be serialised into the internal Union buffer.
- If you are serialising custom types make sure you test it properly incase there are any fields that
cannot be serialised.