ObjectBox Docs
HomeBlogTwitterGitHub
  • ObjectBox Docs
  • Getting started
  • Tutorial: Demo Project
  • Entity Annotations
  • Android (Java/Kotlin)
    • Android Local Unit Tests
    • LiveData (Arch. Comp.)
    • Paging (Arch. Comp.)
    • App Bundle, split APKs and LinkageError
    • greenDAO Compat
  • Desktop Apps
  • Kotlin Support
  • ObjectBox Queries
  • On-Device Vector Search
  • Data Observers & Rx
  • Relations
  • ObjectBox Admin
  • Transactions
  • Advanced
    • Advanced Setup
    • Object IDs
    • Custom Types
    • Entity Inheritance
    • Data Model Updates
    • Meta Model, IDs, and UIDs
  • Changelogs
  • Java API reference
  • Dart API reference
  • Python API reference
  • Binary License
  • FAQ
  • Troubleshooting
  • Data Sync
  • Swift Database for iOS
  • C++ Database Docs
  • Java Release History (<= v1.5)
Powered by GitBook
On this page
  • ObjectBox and Kotlin
  • Kotlin Entities
  • Defining Relations in Kotlin Entities
  • Using the provided extension functions
  • Queries
  • Relations
  • Flow
  • Coroutines
  • Next Steps

Was this helpful?

Export as PDF

Kotlin Support

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.

PreviousDesktop AppsNextObjectBox Queries

Last updated 12 months ago

Was this helpful?

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.

Kotlin Entities

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. are abstract and can't be instantiated. But subclasses of a sealed class should work.

To learn how to create entities, look at these pages:

Defining Relations in Kotlin Entities

When in Kotlin, keep in mind that relation properties must be var. Otherwise they can not be initialized as described in the . To avoid null checks use a lateinit modifier. When using a data class this requires the relation property to be moved to the body.

For non-Android projects, i.e. if you are using Kotlin for desktop apps, there's an additional setup for for entities necessary, please see for details. In the future, we hope to eliminate this requirement.

See the Relations page for examples.

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:

dependencies {
    implementation("io.objectbox:objectbox-kotlin:$objectboxVersion")
}

Now have a look at what is possible with the extensions compared to standard Kotlin idioms:

Get a box:

// Regular:
val box = store.boxFor(DataClassEntity::class.java)

// With extension:
val box: Box<DataClassEntity> = store.boxFor()

Queries

Build a query:

// Regular:
val query = box.query().run {
    equal(property, value)
    order(property)
    build()
}

// With extension:
val query = box.query {
    equal(property, value)
    order(property)
}

Use the in filter of a query:

// Regular:
val query = box.query().`in`(property, array).build()

// With extension:
val query = box.query().inValues(property, array).build()

Relations

// Regular:
toMany.apply { 
    reset()
    add(entity)
    removeById(id)
    applyChangesToDb()
}

// With extension:
toMany.applyChangesToDb(resetFirst = true) { // default is false
    add(entity)
    removeById(id)
}

Flow

// Listen to all changes to a Box
val flow = store.subscribe(TestEntity::class.java).toFlow()
// Get the latest query results on any changes to a Box
val flow = box.query().subscribe().toFlow()

Coroutines

To run Box operations on a separate Dispatcher wrap them using withContext:

suspend fun putNote(
    note: Note, 
    dispatcher: CoroutineDispatcher
) = withContext(dispatcher) {
    boxStore.boxFor(Note::class.java).put(note)
}

BoxStore provides an async API to run transactions. There is an extension function available that wraps it in a coroutine:

// Calls callInTxAsync behind the scenes.
val id = boxStore.awaitCallInTx {
    box.put(Note("Hello", 1))
}

Next Steps

Two data classes that have the same property values (excluding those defined in the class body) . 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.

The makes below extensions functions unnecessary.

Modify a :

Get a Flow from a Box or Query subscription (behind the scenes this is based on a ):

Something missing? what other extension functions you want us to add.

Check out the .

Continue with .

Relations
are equal and have the same hash code
Data Observer
Let us know
Kotlin example on GitHub
Getting Started
Getting started
Sealed classes
Getting started
Entity Annotations
defining relations
https://docs.objectbox.io/relations#initialization-magic
new Query API
relations docs
ToMany