flatbuffers
flatbuffers copied to clipboard
[Kotlin] generated code: <field>AsByteBuffer throws NullPointerException when field is null
When using Kotlin code generated by flatc, calling <field>AsByteBuffer on a nullable string field throws a NullPointerException. The Java generated code for the same schema correctly returns null.
Steps to Reproduce:
Schema (nullable_string.fbs):
table NullableString {
value:string;
}
root_type NullableString;
Kotlin code:
package org.example
import com.google.flatbuffers.FlatBufferBuilder
import java.nio.ByteBuffer
fun serialize(): ByteBuffer {
val builder = FlatBufferBuilder()
val offset = NullableStringKotlin.createNullableString(builder, 0)
builder.finish(offset)
return builder.dataBuffer()
}
fun main() {
val javaRoot = NullableStringJava.getRootAsNullableString(serialize())
println(javaRoot.value()) // prints "null"
println(javaRoot.valueAsByteBuffer()) // prints "null"
val kotlinRoot = NullableStringKotlin.getRootAsNullableString(serialize())
println(kotlinRoot.value) // prints "null"
println(kotlinRoot.valueAsByteBuffer) // accessing this property throws NullPointerException
}
Output:
null
null
null
Exception in thread "main" java.lang.NullPointerException: __vector_as_bytebuffer(...) must not be null
at org.example.NullableStringKotlin.getValueAsByteBuffer(NullableStringKotlin.kt:28)
at org.example.MainKt.main(Main.kt:20)
at org.example.MainKt.main(Main.kt)
Expected Behavior: Kotlin generated code should behave the same as Java generated code, returning null when the field is not present.
Environment:
- flatc version: 25.2.10
- FlatBuffers library: com.google.flatbuffers:flatbuffers-java:25.2.10
- Kotlin version: 2.2.0
- Language: Kotlin + Java interop
- JVM: Microsoft OpenJDK 17.0.15
- OS: Windows 11
Possible Fix Change the generated Kotlin code to return a nullable type. Instead of:
val valueAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1)
Change to:
val valueAsByteBuffer : ByteBuffer? get() = __vector_as_bytebuffer(4, 1)
This removes the null check that Kotlin automatically performs.