Docs Menu

Docs HomeRealm

Create Realm Objects - Kotlin SDK

On this page

  • Create an Object with a Dictionary Property

Note

You can only insert new objects into a realm within a write transaction.

Instantiate Realm objects as you would any other object. In a transaction, you can add the object to the realm if the realm's schema includes the object type. When you add an instance to the realm, it becomes managed by that realm.

To persist a new object to a realm:

  1. Instantiate a new object instance with the class constructor. You can use an apply block to configure multiple properties at once.

  2. Open a write transaction with realm.write() or realm.writeBlocking().

  3. Pass the new object instance to copyToRealm() to persist the object data to the realm. This method returns a managed instance of the object. You can modify the persisted object through the returned instance.

realm.write {
this.copyToRealm(Frog().apply {
name = "Kermit"
age = 45
species = "Green"
owner = "Jim"
})
}

You can create objects with RealmDictionary properties. The RealmDictionary keys may only be strings, but values may be any type of Realm-supported primitive, a RealmObject, or an EmbeddedObject.

For more information about defining a dictionary property, refer to RealmDictionary/RealmMap.

realm.write {
this.copyToRealm(Frog().apply {
name = "Kermit"
favoritePondsByForest = realmDictionaryOf("Hundred Acre Wood" to "Picnic Pond", "Lothlorien" to "Linya")
})
}
←  Read & Write Data - Kotlin SDKRead Realm Objects - Kotlin SDK →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.