Value types / structs

I love Kotlin, I love its language design, and I really really love that it can run on both natively and both on a mashine.

There is just one thing that really bothers me though, that there are no struct or in-place classes. Well you might ask yourself what are they?

Structs are like classes, just they don’t get allocated when a new one is created. Also they are in-place, that means that in a function, they are allocated on a stack, or staticly, or when they are in a class the place is reserved for the data types. That means that there is no garbage collection for structs. Especially for game development struct types are highly necessary in order to drastically improve performance. Structs have some disadvantages though, they can get inherite, but they can implement interfaces. Also structs can have @ attributes that can determine the struct layout, for C++ and native compatibility reasons.

With structs, there are also struct references and nullable structs. Struct references store a reference to a struct, they act like pointers. The compiler warns the user if a unsafe struct reference is being created.

Assigning a struct to another struct will copy the struct.

Structs would make Kotlin so much useable in terms of performance and could even replace most of the C++ backend code.

Here is an example where structs are much better than classes:

If you have a Vector3 type you want it to be fast and efficient, but allocating every time when creating a Vector3 is just stupid and wasting of performance, because there are like just float 3 values.

Or let’s say you are writing a render api for rendering. You would mostly use structs there instead of classes, so that memory allocation is low for good performance.

Dear Kotlin team, you are making a phantastic job, but please add this wonderful feature (◠‿◕)

Your description of this “feature” is a bit confusing, it seems you’re mixing “allocating on the heap” and “value classes”.
Kotlin has inline classes which are a subset of value classes already: Inline classes | Kotlin

And at some point - on the JVM - at least, via project Valhalla Kotlin will have full value classes.

I am not mixing them. I am saying that structs are in-place value types. That means that when they are lonely in a function or static, the place is there. The same goes for classes, but the place is also allocated with the class itself, just like in C#

Please see Kotlin’s inline/value classes:

1 Like