Create Realm Objects - Kotlin SDK
On this page
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:
Instantiate a new object instance with the class constructor. You can use an apply block to configure multiple properties at once.
Open a write transaction with realm.write() or realm.writeBlocking().
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" }) }
Create an Object with a Dictionary Property
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") }) }