How to implement a Kotlin property through JNI?

Issue

In Kotlin, I can use the external keyword to delegate the implementation of a function to native code. Given that Kotlin properties are mere syntactic sugar for a pair of getter and setter functions, I assumed that it should be possible to implement a property using native code, too. However, I can’t seem to figure out how.

If I prefix the get and set keywords with external, Kotlin tells me that it’s expecting a function body:

Of course, the whole point is not to have a function body in Kotlin. But if I add one anyway, Kotlin (rather expectedly) tells me that external declarations cannot have a body:

Is my syntax wrong? Or is there simply no way to implement a Kotlin property using JNI?

Solution

I found the solution! It is possible to implement properties via JNI, I was just using the wrong syntax! The correct syntax is:

class Test {
    var value: Int
        external get // No parentheses or parameter list!
        external set
}

This syntax doesn’t seem to be documented yet.

Edit: I created a PR for the Kotlin documentation, which has been merged. So now this feature is officially documented.

Answered By – Daniel Wolf

Leave a Comment