So in Kotlin 1.4.30, some changes occurred with inline classes, mostly for futureproofing with regard to JVM value classes. However, among these changes is a new warning issued whenever you declare a ‘var’ type property on an inline class:
Kotlin: ‘var’ properties with value class receivers are reserved for future use.
This implies that a very helpful use-case may be deprecated in the future. Suppose I’m working with JNI, where addresses are frequently passed and returned via Longs. In such a context, this syntax is very intuitive and helpful:
inline class Grid(val ptr: Long) {
var width: Int
get() = GridNative.getWidth(ptr)
set(v) { GridNative.setWidth(ptr, v) }
}
Another example is in the context of sun.misc.Unsafe. (I know what you’re thinking, but bear with me.) In my case, it’s necessary in the context of game development, communicating with C++ libraries, etc, in a way that’s reasonably fast enough for a game engine. The popular library LWJGL, included in Minecraft and which makes use of Kotlin, also makes abundant use of Unsafe. So granted that, suppose I were to generate code like this:
inline class Vertex(val ptr: Long) {
var x get() = UNSAFE.getFloat(ptr + 0); set(v) { UNSAFE.putFloat(ptr + 0) }
var y get() = UNSAFE.getFloat(ptr + 4); set(v) { UNSAFE.putFloat(ptr + 4) }
var z get() = UNSAFE.getFloat(ptr + 8); set(v) { UNSAFE.putFloat(ptr + 8) }
}
Suddenly I could work with “arrays of structs” in a relatively safe and intuitive fashion, all while staying performant due to JVM method inlining! And this is in fact what I’m currently doing. The alternative of defining a bunch of methods would be quite stifling, especially considering the utility of compound assignment operators.
Now you might be tempted to argue that value classes would fill this void, but so long as they’re allocated on the JVM heap, they cannot be passed to OpenGL or other graphics libraries to transfer the data to the graphics card. (Since value classes can refer to non-value classes, one would assume that they will not in fact be allocatable in native memory, at least not without an ‘unsafe’ construct similar to C#.) There are also currently no JVM guarantees on the ordering of fields in memory!
All this is to say: What can we expect from this warning? Will ‘var’ be converted to a compile-time error in Kotlin 1.5, or can I safely suppress this warning and go along my merry, hacky way? As long as it doesn’t become completely disallowed, I’ll be happy.