Navigation

Quick Start - Kotlin Multiplatform SDK

On this page

  • Define Your Object Model
  • Open a Realm
  • Create, Read, Update, and Delete Objects
  • Complete Example

This page contains information to quickly get Realm Database integrated into your app. Before you begin, ensure you have:

Your application's data model defines the structure of data stored within Realm Database. You can define your application's data model via Kotlin classes in your application code with Realm Object Models.

To define your application's data model, add the following class definition to your application code:

class Task : RealmObject {
var name: String = "new task"
var status: String = "Open"
}

Use RealmConfiguration to control the specifics of the realm you would like to open, including the name, location, and schema. Pass your configuration to the Realm constructor to generate an instance of that realm:

val config = RealmConfiguration(schema = setOf(Task::class))
val realm = Realm(config)

Once opened, you can create objects within a realm in a write transaction block.

To create a new Task, instantiate an instance of the Task class and add it to the realm in a write transaction block:

realm.writeBlocking {
this.copyToRealm(Task().apply {
name = "Do work"
status = "Open"
})
}

You can retrieve a collection of all tasks in the realm:

// all tasks in the realm
val tasks = realm.objects<Task>().query()

You can also filter a collection to retrieve a more specific collection of objects:

// all tasks in the realm
val tasksThatBeginWIthD = realm.objects<Task>().query("name BEGINSWITH $0'", "D")
val openTasks = realm.objects<Task>().query("status == $0", "Open")
Note
Realm Query Language

You can find more information about string Realm Database queries in the Node SDK Query Guide.

To modify a task, update its properties in a write transaction block:

realm.writeBlocking {
openTasks[0].status = "In Progress"
}

Finally, you can delete a task by calling the object.delete() method in a write transaction block:

realm.writeBlocking {
tasks[0].delete()
}

If you're running this project in a fresh KMM template project, you can copy and paste into the Greeting.greeting() method in the commonMain module.

val config = RealmConfiguration(schema = setOf(Task::class))
val realm = Realm(config)
realm.writeBlocking {
this.copyToRealm(Task().apply {
name = "Do work"
status = "Open"
})
}
// all tasks in the realm
val tasks = realm.objects<Task>().query()
// all tasks in the realm
val tasksThatBeginWIthD = realm.objects<Task>().query("name BEGINSWITH $0'", "D")
val openTasks = realm.objects<Task>().query("status == $0", "Open")
realm.writeBlocking {
openTasks[0].status = "In Progress"
}
realm.writeBlocking {
tasks[0].delete()
}
Give Feedback

On this page

  • Define Your Object Model
  • Open a Realm
  • Create, Read, Update, and Delete Objects
  • Complete Example