UUID - Kotlin SDK
On this page
UUID
(Universal Unique Identifier) is a 16-byte unique value. You can use UUID
as an identifier for
objects. UUID
is indexable, and you can use it as a
primary key.
Realm Database creates UUIDs with the RealmUUID type that:
conform to RFC 4122 version 4
are created with random bytes
class Cat: RealmObject { var _id: RealmUUID = RealmUUID.random() }
Note
Using UUID Instead of ObjectId
In general, you can use UUID
for any fields that function as a unique
identifier. Using UUID
might be particularly useful if you are migrating
data not stored in MongoDB since it is likely that your object's unique
identifiers are already of a UUID
type. Alternatively, using ObjectId
might be useful for a collection of data that already exists in MongoDB.
Create a UUID from a String
To generate a new RealmUUID
from a UUID formatted string, pass the string to RealmUUID.from():
realm.write { this.copyToRealm(Cat().apply { _id = RealmUUID.from("46423f1b-ce3e-4a7e-812f-004cf9c42d76") }) }
Create a Random UUID
To generate a random RealmUUID
, call RealmUUID.random():
realm.write { this.copyToRealm(Cat().apply { _id = RealmUUID.random() }) }