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.

Setup

The setup is identical to that of a Java-only project, see the Introduction page. However, we provide a tiny additional library with a few Kotlin extension functions. We intend to grow it in the future, so let us know what you want to see in it. Just add it to your module dependencies:

Once you got the build working it is time to look at how to define entities in Kotlin.

Kotlin Entities

In Kotlin, you should define ID properties like this:

The ID must be a var (not a val) because ObjectBox assigns an ID after putting a new entity. Also, IDs should be of primitive type Long with the special value of zero for marking entities as new.

So a simple data class looks like this:

Entity Constructors

ObjectBox needs to call a constructor to create objects. It will choose one of these two:

  • All-args constructor: If ObjectBox finds a constructor that matches all persisted properties (types and names are checked), it will call it preferably.
  • No-args constructor: fall back if it does not find an all-args constructor. ObjectBox will initialize fields after calling the no-args (default) constructor.

Note that Kotlin data classes usually provide a compatible all-args constructor. However, ObjectBox can not use it if  transient properties or relations are part of the constructor parameters.

Defining Relations in Kotlin Entities

Defining relation in Kotlin pretty much works like ObjectBox relations in standard Java. In Kotlin, you typically would use a lateinit  modifier for relation properties. The same “initialization magic” applies as described in the above link.

Example:

 

Spread the love