Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
Datos del modelo

Supported Types - Kotlin SDK

This page describes the supported data types that you can use to define properties in your object model. For more information on how to define your object model, refer to Define an Object Model.

Para obtener información sobre cómo se asignan tipos de datos específicos a tipos BSON en un esquema de App Services, consulte Mapeo de modelos de datos en la documentación de Atlas App Services.

El SDK de Kotlin admite los siguientes tipos de Kotlin, tiposBSON y tipos específicos de reino, que puede utilizar para identificadores únicos, marcas de tiempo, contadores y colecciones.

The Kotlin SDK does not natively support:

  • propiedades de enumeración definidas por el usuario. Consulta la sección Enum para obtener más información sobre el uso de enums en tus objetos Realm.

  • Integrado en Kotlin Date Instanto. Consulte la sección RealmInstant para obtener más información sobre cómo usar marcas de tiempo en sus objetos Realm.

Realm object properties must be mutable and initialized when declared. The Kotlin SDK does not currently support abstract properties. You can declare properties optional (nullable) using the built-in ? Kotlin operator, or you can assign a default value to a property when you declare it.

Nota

Realm stores all non-decimal numeric types as Long values and all decimal numeric types as Double values.

Kotlin Data Types

The following table lists the supported Kotlin data types and examples of how to declare them as required or optional properties in your object model.

Tipo de datos de Kotlin
Requerido
Opcional

String

var stringReq: String = ""
var stringOpt: String? = null

Byte

var byteReq: Byte = 0
var byteOpt: Byte? = null

Short

var shortReq: Short = 0
var shortOpt: Short? = null

Int

var intReq: Int = 0
var intOpt: Int? = null

Long

var longReq: Long = 0L
var longOpt: Long? = null

Float

var floatReq: Float = 0.0f
var floatOpt: Float? = null

Double

var doubleReq: Double = 0.0
var doubleOpt: Double? = null

Boolean

var boolReq: Boolean = false
var boolOpt: Boolean? = null

Char

var charReq: Char = 'a'
var charOpt: Char? = null

MongoDB BSON Types

The following table lists the supported MongoDB BSON data types and examples of how to declare them as required or optional properties in your object model. To use these types, you must import them from the org.mongodb.kbson package.

Tipo BSON de MongoDB
Requerido
Opcional
var objectIdReq: ObjectId = ObjectId()
var objectIdOpt: ObjectId? = null

Decimal128

var decimal128Req: Decimal128 = Decimal128("123.456")
var decimal128Opt: Decimal128? = null

Tipos específicos de Realm

La siguiente tabla enumera los tipos de datos específicos de Realm admitidos y ejemplos de cómo declararlos como propiedades obligatorias u opcionales en tu modelo de objeto.

Realm-Specific Type
Requerido
Opcional
var uuidReq: RealmUUID = RealmUUID.random()
var uuidOpt: RealmUUID? = null
var realmInstantReq: RealmInstant = RealmInstant.now()
var realmInstantOpt: RealmInstant? = null

N/A

var realmAnyOpt: RealmAny? = RealmAny.create("foo")
var mutableRealmIntReq: MutableRealmInt = MutableRealmInt.create(0)
var mutableRealmIntOpt: MutableRealmInt? = null
var listReq: RealmList<CustomObjectType> = realmListOf()

N/A

var setReq: RealmSet<String> = realmSetOf()

N/A

var dictionaryReq: RealmDictionary<String> = realmDictionaryOf()

N/A

N/A

var realmObjectPropertyOpt: CustomObjectType? = null

N/A

var embeddedProperty: EmbeddedObjectType? = null

El SDK de Kotlin admite UUID y ObjectId como identificadores únicos para objetos de Realm.

Nota

Uso de UUID en lugar de 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.

ObjectId is a MongoDB-specific BSON type. It is a 12-byte, globally unique value that you can use as an identifier for objects. It is nullable, indexable, and can be used as a primary key.

You can initialize an ObjectId using ObjectId().

Importante

io.realm.kotlin.types.ObjectId Deprecated in v1.5.0

In Realm Kotlin SDK version 1.5.0 and newer, io.realm.kotlin.types.ObjectId is deprecated. You must import ObjectId from org.mongodb.kbson.ObjectId instead.

UUID (Universal Unique Identifier) is a 16-byte unique value that you can use as an identifier for objects. It is nullable, indexable, and can be used as a primary key.

Realm crea UUIDs con el tipo RealmUUID que se ajustan a RFC 4122 versión 4 y se crean con bytes aleatorios.

You can generate a random RealmUUID using RealmUUID.random() or pass a UUID-formatted string to RealmUUID.from():

val uuid1 = RealmUUID.from("46423f1b-ce3e-4a7e-812f-004cf9c42d76")
val uuid2 = RealmUUID.random()

El SDK de Kotlin ofrece MutableRealmInt como un tipo de entero especial que puedes usar como contador lógico para sincronizar con precisión los cambios numéricos entre diversos clientes distribuidos. Se comporta como un Long, pero también admite los métodos increment y decrement que implementan un tipo de datos replicados sin conflictos. Esto garantiza que las actualizaciones numéricas puedan ejecutarse independientemente del orden para converger en el mismo valor.

A MutableRealmInt property:

  • cannot be used as a primary key

  • no puede almacenar valores nulos, pero puede declararse anulable (MutableRealmInt?)

Additionally, MutableRealmInt fields:

  • are backed by Kotlin's numeric types, so no migration is required when changing a numeric field to MutableRealmInt.

  • can use operators and infix functions similar to those provided by Long. However, note that any operations other than set, increment, and decrement do not mutate the instance on which they are executed. Instead, they create a new, unmanaged MutableRealmInt instance with the updated value.

Learn how to Create a MutableRealmInt (Counter) Property and Update a MutableRealmInt (Counter) Property.

You cannot store Kotlin's built-in Date or Instant types in Realm.

Instead, the Kotlin SDK uses the RealmInstant type to store time information as a Unix epoch timestamp.

If you need timestamp data in a form other than RealmInstant, you can add conversion code to your model class based on the following example:

// model class that stores an Instant (kotlinx-datetime) field as a RealmInstant via a conversion
class RealmInstantConversion : RealmObject {
private var _timestamp: RealmInstant = RealmInstant.from(0, 0)
public var timestamp: Instant
get() {
return _timestamp.toInstant()
}
set(value) {
_timestamp = value.toRealmInstant()
}
}
fun RealmInstant.toInstant(): Instant {
val sec: Long = this.epochSeconds
// The value always lies in the range `-999_999_999..999_999_999`.
// minus for timestamps before epoch, positive for after
val nano: Int = this.nanosecondsOfSecond
return if (sec >= 0) { // For positive timestamps, conversion can happen directly
Instant.fromEpochSeconds(sec, nano.toLong())
} else {
// For negative timestamps, RealmInstant starts from the higher value with negative
// nanoseconds, while Instant starts from the lower value with positive nanoseconds
// TODO This probably breaks at edge cases like MIN/MAX
Instant.fromEpochSeconds(sec - 1, 1_000_000 + nano.toLong())
}
}
fun Instant.toRealmInstant(): RealmInstant {
val sec: Long = this.epochSeconds
// The value is always positive and lies in the range `0..999_999_999`.
val nano: Int = this.nanosecondsOfSecond
return if (sec >= 0) { // For positive timestamps, conversion can happen directly
RealmInstant.from(sec, nano)
} else {
// For negative timestamps, RealmInstant starts from the higher value with negative
// nanoseconds, while Instant starts from the lower value with positive nanoseconds
// TODO This probably breaks at edge cases like MIN/MAX
RealmInstant.from(sec + 1, -1_000_000 + nano)
}
}

Cambiado en la versión 2.0.0: RealmAny puede contener listas y diccionarios de datos mixtos.

RealmAny representa un tipo de datos mixtos no nulo. Se comporta como la variable de valor que contiene. RealmAny puede contener:

  • supported Kotlin data types (note that Byte, Char, Int, Long, and Short values are converted internally to int64_t values)

  • supported BSON types

  • RealmList y RealmDictionary colecciones de datos mixtos

  • the following Realm-specific types:

    • RealmInstant

    • RealmUUID

    • RealmObject (holds a reference to the object, not a copy of it)

RealmAny cannot hold EmbeddedRealmObject types, RealmSet, or another RealmAny.

RealmAny propiedad:

You can store multiple RealmAny instances in RealmList, RealmDictionary, or RealmSet fields.

Tip

Handle Polymorphism with Conditional Expressions

Because you must know the stored type to extract its value, we recommend using a when expression to handle the RealmAny type and its possible inner value class.

In version 2.0.0 and later, a RealmAny data type can hold collections (a list or dictionary, but not a set) of RealmAny elements. You can use mixed collections to model unstructured or variable data. For more information, refer to Define Unstructured Data.

  • Se pueden anidar colecciones mixtas hasta 100 niveles.

  • You can query mixed collection properties and register a listener for changes, as you would a normal collection.

  • You can find and update individual mixed collection elements

  • You cannot store sets or embedded objects in mixed collections.

To use mixed collections in your app, define the mixed type property in your data model the same way you would any other RealmAny type. Then, create the list or dictionary collections using RealmAny.create().

The Kotlin SDK offers several collection types that you can use as properties in your data model. A collection is an object that contains zero or more instances of one supported data type. Realm collections are homogenous (all objects in a collection are of the same type) and are backed by their corresponding built-in Kotlin classes.

Collection types are non-null. When you define a collection property, you must initialize it. For more information, refer to Create a Collection.

The RealmList type implements Kotlin's List interface. Unmanaged lists behave like Kotlin's MutableList.

Un RealmList representa una relación de uno a muchos que contiene:

RealmList<E> is a non-null type, where:

  • lists of RealmObject or EmbeddedRealmObject elements cannot be nullable

  • lists of any other supported elements can be nullable (RealmList<E?>)

The RealmSet type implements Kotlin's Set interface. Unmanaged sets behave like Kotlin's MutableSet.

Un RealmSet representa una relación de muchos que contiene valores distintos de:

You cannot use EmbeddedRealmObject elements in a RealmSet.

RealmSet<E> is a non-null type, where:

  • sets of RealmObject elements cannot be nullable

  • sets of any other supported elements can be nullable (RealmSet<E?>)

El tipo RealmMap implementa la interfaz Map de Kotlin y es un arreglo asociativo que contiene pares clave-valor String con claves únicas. RealmDictionary es un RealmMap especializado que acepta una clave String y valores no string. Diccionarios no gestionados se comportan como LinkedHashMapde Kotlin.

RealmDictionary values can be:

RealmDictionary<K, V> is a non-null type, where:

  • keys must be strings

  • RealmObject o los valores de EmbeddedRealmObject deben ser nulos (RealmDictionary<K, V?>)

  • any other supported element values can be nullable

Puedes usar RealmObject y cualquier subclase, excepto AsymmetricRealmObject como propiedades en tu modelo de objetos.

Importante

AsymmetricRealmObject cannot be used as properties. For more information, refer to Asymmetric Objects.

A RealmObject type represents a custom object that you can use as a property.

RealmObject propiedad:

  • must be declared nullable

  • can be used as elements in collections

  • can be held as a RealmAny value

  • cannot be used as a primary key

You can also reference one or more Realm objects from another through to-one and to-many relationships. For more information, refer to the Relationships page.

Un vínculo inverso representa una relación inversa de muchos a muchos entre un RealmObject y uno o más RealmObject o entre un RealmObject y un EmbeddedRealmObject. Los vínculos inversos no pueden ser nulos.

Backlinks implement:

For more information, refer to Inverse Relationships.

Un EmbeddedRealmObject es un tipo especial de RealmObject.

EmbeddedRealmObject propiedad:

  • must be nullable objects within the parent object

  • must be nullable values within a dictionary

  • cannot be nullable elements within a list

  • cannot be used as a primary key

  • can be properties within an asymmetric object

For more information, refer to Embedded Objects.

New in version 1.11.0.

The Kotlin SDK supports geospatial queries using the following data types:

Importante

Cannot Persist Geospatial Data Types

Currently, geospatial data types cannot be persisted. For example, you can't declare a property that is of type GeoBox.

Estos tipos solo pueden utilizarse como argumentos para consultas geoespaciales.

For more information on querying with geospatial data, refer to Geospatial Data.

The Kotlin SDK does not natively support enumerations, or enums. To use enums in a Realm object class, define a field with a type matching the underlying data type of your enum.

Then, create getters and setters for the field that convert the field value between the underlying value and the enum type.

enum class EnumClass(var state: String) {
NOT_STARTED("NOT_STARTED"),
IN_PROGRESS("IN_PROGRESS"),
COMPLETE("COMPLETE")
}
class EnumObject : RealmObject {
var name: String? = null
private var state: String = EnumClass.NOT_STARTED.state
var stateEnum: EnumClass
get() = EnumClass.valueOf(state)
set(value) {
state = value.state
}
}

Volver

Define un modelo de objeto

En esta página