ObjectBox fully supports Kotlin for Android. Learn what to look out for when using ObjectBox with Kotlin, how to use the built-in Kotlin extension functions.
ObjectBox and Kotlin
ObjectBox comes with full Kotlin support for Android. This allows entities to be modeled in Kotlin classes (regular and data classes). With Kotlin support you can build faster apps even faster.
This page assumes that you have added ObjectBox to your project and that you are familiar with basic functionality. The Getting Started page will help you out if you are not. This page discusses additional capabilities for Kotlin only.
ObjectBox supports regular and data classes for entities. However, @Id properties must be var (not val) because ObjectBox assigns the ID after putting a new entity. They also should be of non-null type Long with the special value of zero for marking entities as new.
Can sealed classes be entities? Not directly. Sealed classes are abstract and can't be instantiated. But subclasses of a sealed class should work.
When defining relations in Kotlin, keep in mind that relation properties must be var. Otherwise they can not be initialized as described in the relations docs. To avoid null checks use a lateinit modifier. When using a data class this requires the relation property to be moved to the body.
Two data classes that have the same property values (excluding those defined in the class body) are equal and have the same hash code. Keep this in mind when working with ToMany which uses a HashMap to keep track of changes. E.g. adding the same data class multiple times has no effect, it is treated as the same entity.
Using the provided extension functions
To simplify your code, you might want to use the Kotlin extension functions provided by ObjectBox. The library containing them is added automatically if the Gradle plugin detects a Kotlin project.
To add it manually, modify the dependencies section in your app's build.gradle file: