# Realm Data Types

## Introduction

A key feature of Realm is you don’t have to think about converting data to/from JSON, or using ORMs. Just create your objects using the data types your language natively supports. We’re adding new supported types to all our SDKs, here is a refresher and a taste of the new supported types.

## Swift: Already supported types

The complete reference of supported data types for iOS can be found here.

| Type Name | Code Sample |
| --------- | ----------- |
| Bool
A value type whose instances are either true or false. | `// Declaring as Required`
`@objc dynamic var value = false`

`// Declaring as Optional`
`let value = RealmProperty()` |
| Int, Int8, Int16, Int32, Int64
A signed integer value type. | `// Declaring as Required`
`@objc dynamic var value = 0`

`// Declaring as Optional`
`let value = RealmProperty()` |
| Float
A single-precision, floating-point value type. | `// Declaring as Required` 
`@objc dynamic var value: Float = 0.0`

`// Declaring as Optional` `let value = RealmProperty()` |
| Double
A double-precision, floating-point value type. | `// Declaring as Required`
`@objc dynamic var value: Double = 0.0`

`// Declaring as Optional`
`let value = RealmProperty()` |
| String
A Unicode string value that is a collection of characters. | `// Declaring as Required`
`@objc dynamic var value = ""`

`// Declaring as Optional`
`@objc dynamic var value: String? = nil` |
| Data
A byte buffer in memory. | `// Declaring as Required`
`@objc dynamic var value = Data()`

`// Declaring as Optional`
`@objc dynamic var value: Data? = nil` |
| Date
A specific point in time, independent of any calendar or time zone. | `// Declaring as Required`
`@objc dynamic var value = Date()`

`// Declaring as Optional`
`@objc dynamic var value: Date? = nil` |
| Decimal128
A structure representing a base-10 number. | `// Declaring as Required`
`@objc dynamic var decimal: Decimal128 = 0`

`// Declaring as Optional`
`@objc dynamic var decimal: Decimal128? = nil` |
| List
List is the container type in Realm used to define to-many relationships. | `let value = List()` |
| ObjectId
A 12-byte (probably) unique object identifier. Compatible with the ObjectId type used in the MongoDB database. | `// Declaring as Required`
`@objc dynamic var objectId = ObjectId.generate()`

`// Declaring as Optional`
`@objc dynamic var objectId: ObjectId? = nil` |
| User-defined Object Your own classes. | `// Declaring as Optional`
`@objc dynamic var value: MyClass? = nil` |

## Swift: New Realm Supported Data Types

Starting with **Realm iOS 10.8.0**

| Type Name | Code Sample |
| --------- | ----------- |
| Maps 
Store data in arbitrary key-value pairs. They’re used when a developer wants to add flexibility to data models that may evolve over time, or handle unstructured data from a remote endpoint. | `class Player: Object {` 
 `@objc dynamic var name = String?`
 `@objc dynamic var email: String?`
 `@objc dynamic var playerHandle: String?`
 `let gameplayStats = Map()`
 `let competitionStats = Map()`
`}`
`try! realm.write {`
 `let player = Player()`
 `player.name = "iDubs"`

 `// get the RealmDictionary field from the object we just created and add stats`
 `let statsDictionary = player.gameplayStats`
 `statsDictioanry"mostCommonRole"] = "Medic"`
 `statsDictioanry["clan"] = "Realmers"`
 `statsDictioanry["favoriteMap"] = "Scorpian bay"`
 `statsDictioanry["tagLine"] = "Always Be Healin"`
 `statsDictioanry["nemesisHandle"] = "snakeCase4Life"`
 `let competitionStats = player.comeptitionStats`

 `competitionStats["EastCoastInvitational"] = "2nd Place"`
 `competitionStats["TransAtlanticOpen"] = "4th Place"`
`}` |
| [MutableSet 
MutableSet is the container type in Realm used to define to-many relationships with distinct values as objects. | `// MutableSet declaring as required` 
`let value = MutableSet()`

`// Declaring as Optional`
`let value: MutableSet? = nil `|
| AnyRealmValue 
AnyRealmValue is a Realm property type that can hold different data types. | `// Declaring as Required` 
`let value = RealmProperty()`

`// Declaring as Optional`
`let value: RealmProperty? = nil` |
| UUID 
UUID is a 16-byte globally-unique value. | `// Declaring as Required` 
`@objc dynamic var uuid = UUID()`

`// Declaring as Optional`
`@objc dynamic var uuidOpt: UUID? = nil` |

## Android/Kotlin: Already supported types

You can use these types in your RealmObject subclasses. The complete reference of supported data types for Kotlin can be found here.

| Type Name | Code Sample |
| --------- | ----------- |
| Boolean or boolean
Represents boolean objects that can have two values: true and false. | `// Declaring as Required` 
`var visited = false`

`// Declaring as Optional`
`var visited = false` |
| Integer or int
A 32-bit signed number. | `// Declaring as Required` 
`var number: Int = 0`

`// Declaring as Optional`
`var number: Int? = 0` |
| Short or short
A 16-bit signed number. | `// Declaring as Required` 
`var number: Short = 0`

`// Declaring as Optional`
`var number: Short? = 0` |
| Long or long
A 64-bit signed number. | `// Declaring as Required` 
`var number: Long = 0`

`// Declaring as Optional`
`var number: Long? = 0` |
| Byte or byte]
A 8-bit signed number. | `// Declaring as Required` 
`var number: Byte = 0`

`// Declaring as Optional`
`var number: Byte? = 0` |
| [Double or double
Floating point number(IEEE 754 double precision) | `// Declaring as Required` 
`var number: Double = 0`

`// Declaring as Optional`
`var number: Double? = 0.0` |
| Float or float
Floating point number(IEEE 754 single precision) | `// Declaring as Required` 
`var number: Float = 0`

`// Declaring as Optional`
`var number: Float? = 0.0` |
| String | `// Declaring as Required` 
`var sdkName: String = "Realm"`

`// Declaring as Optional`
`var sdkName: String? = "Realm"` |
| Date | `// Declaring as Required` 
`var visited: Date = Date()`

`// Declaring as Optional`
`var visited: Date? = null` |
| Decimal128 from org.bson.types
A binary integer decimal representation of a 128-bit decimal value | `var number: Decimal128 = Decimal128.POSITIVE_INFINITY` |
| ObjectId from org.bson.types
A globally unique identifier for objects. | `var oId = ObjectId()` |
| Any RealmObject subclass | `// Define an embedded object` 
`@RealmClass(embedded = true)`
`open class Address(`
 `var street: String? = null,`
 `var city: String? = null,`
 `var country: String? = null,`
 `var postalCode: String? = null`
`): RealmObject() {}`
`// Define an object containing one embedded object`
`open class Contact(_name: String = "", _address: Address? = null) : RealmObject() {`
 `@PrimaryKey var _id: ObjectId = ObjectId()`
 `var name: String = _name`

 `// Embed a single object.`
 `// Embedded object properties must be marked optional`
 `var address: Address? = _address`
`}` |
| RealmList 
RealmList is used to model one-to-many relationships in a RealmObject. | `var favoriteColors : RealmList? = null` |

## Android/Kotlin: New Realm Supported Data Types
Starting with **Realm Android 10.6.0**

| Type Name | Code Sample |
| --------- | ----------- |
| RealmDictionary 
Manages a collection of unique String keys paired with values. | `import io.realm.RealmDictionary` 
`import io.realm.RealmObject`

`open class Frog: RealmObject() {`
 `var name: String? = null`
 `var nicknamesToFriends: RealmDictionary = RealmDictionary()`
`}` |
| RealmSet 
You can use the RealmSet data type to manage a collection of unique keys. | `import io.realm.RealmObject` 
`import io.realm.RealmSet`

`open class Frog: RealmObject() {`
 `var name: String = ""`
 `var favoriteSnacks: RealmSet = RealmSet();`
`}` |
| Mixed
RealmAny
You can use the RealmAny data type to create Realm object fields that can contain any of several underlying types. | `import io.realm.RealmAny` 
`import io.realm.RealmObject`

`open class Frog(var bestFriend: RealmAny? = RealmAny.nullValue()) : RealmObject() {`
 `var name: String? = null`
 `open fun bestFriendToString(): String {`
  `if (bestFriend == null) {`
   `return "null"`
  `}`
  `return when (bestFriend!!.type) {`
   `RealmAny.Type.NULL -> {`
    `"no best friend"`
   `}`
   `RealmAny.Type.STRING -> {`
    `bestFriend!!.asString()`
   `}`
   `RealmAny.Type.OBJECT -> {`
    `if (bestFriend!!.valueClass == Person::class.java) {`
     `val person = bestFriend!!.asRealmModel(Person::class.java)`
     `person.name`
    `}`
    `"unknown type"`
   `}`
   `else -> {`
    `"unknown type"`
   `}`
  `}`
 `}`
`}` |
| UUID from java.util.UUID | `var id = UUID.randomUUID()` |

## JavaScript - React Native SDK: : Already supported types

The complete reference of supported data types for JavaScript Node.js can be found here.

| Type Name | Code Sample |
| --------- | ----------- |
| `bool` maps to the JavaScript Boolean type | `var x = new Boolean(false);` |
| `int` maps to the JavaScript Number type. Internally, Realm Database stores int with 64 bits. | `Number('123')` |
| `float` maps to the JavaScript Number type. Internally, Realm Database stores float with 32 bits. | `Number('123.0')` |
| `double` maps to the JavaScript Number type. Internally, Realm Database stores double with 64 bits. | `Number('123.0')` |
| `string` `maps` to the JavaScript String type. | `const string1 = "A string primitive";` |
| `decimal128` for high precision numbers. |  |
| `objectId` maps to BSON `ObjectId` type. | `ObjectId("507f1f77bcf86cd799439011")` |
| `data` maps to the JavaScript ArrayBuffer type. | `const buffer = new ArrayBuffer(8);` |
| `date` maps to the JavaScript Date type. | `new Date()` |
| `list` maps to the JavaScript Array type. You can also specify that a field contains a list of primitive value type by appending ] to the type name. | `let fruits = ['Apple', 'Banana']` |
| `linkingObjects` is a special type used to define an inverse relationship. |  |

## JavaScript - React Native SDK: New Realm supported types

Starting with __Realm JS 10.5.0__

| Type Name | Code Sample |
| --------- | ----------- |
| [dictionary used to manage a collection of unique String keys paired with values. | `let johnDoe;` 
`let janeSmith;`
`realm.write(() => {`
 `johnDoe = realm.create("Person", {`
  `name: "John Doe",`
  `home: {`
   `windows: 5,`
   `doors: 3,`
   `color: "red",`
   `address: "Summerhill St.",`
   `price: 400123,`
  `},`
 `});`
 `janeSmith = realm.create("Person", {`
  `name: "Jane Smith",`
  `home: {`
   `address: "100 northroad st.",`
   `yearBuilt: 1990,`
  `},`
 `});`
`});` |
| set is based on the JavaScript Set type.
A Realm Set is a special object that allows you to store a collection of unique values. Realm Sets are based on JavaScript sets, but can only contain values of a single type and can only be modified within a write transaction. | `let characterOne, characterTwo;` 
`realm.write(() => {`
 `characterOne = realm.create("Character", {`
  `_id: new BSON.ObjectId(),`
  `name: "CharacterOne",`
  `inventory: "elixir", "compass", "glowing shield"],`
  `levelsCompleted: [4, 9],`
 `});`
`characterTwo = realm.create("Character", {`
  `_id: new BSON.ObjectId(),`
 `name: "CharacterTwo",`
  `inventory: ["estus flask", "gloves", "rune"],`
  `levelsCompleted: [1, 2, 5, 24],`
 `});`
`});` |
| [mixed is a property type that can hold different data types.
The mixed data type is a realm property type that can hold any valid Realm data type except a collection. You can create collections (lists, sets, and dictionaries) of type mixed, but a mixed itself cannot be a collection. Properties using the mixed data type can also hold null values. | `realm.write(() => {` 
 `// create a Dog with a birthDate value of type string`
 `realm.create("Dog", { name: "Euler", birthDate: "December 25th, 2017" });`
 `// create a Dog with a birthDate value of type date`
`realm.create("Dog", {`
  `name: "Blaise",`
  `birthDate: new Date("August 17, 2020"),`
 `});`
 `// create a Dog with a birthDate value of type int`
 `realm.create("Dog", {`
  `name: "Euclid",`
  `birthDate: 10152021,`
 `});`
 `// create a Dog with a birthDate value of type null`
  `realm.create("Dog", {`
  `name: "Pythagoras",`
  `birthDate: null,`
 `});`
`});` |
| uuid is a universally unique identifier from Realm.BSON.
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. | `const { UUID } = Realm.BSON;` 
`const ProfileSchema = {`
 `name: "Profile",`
 `primaryKey: "_id",`
 `properties: {`
  `_id: "uuid",`
  `name: "string",`
 `},`
`};`
`const realm = await Realm.open({`
 `schema: ProfileSchema],`
`});`
`realm.write(() => {`
 `realm.create("Profile", {`
  `name: "John Doe.",`
  `_id: new UUID(), // create a _id with a randomly generated UUID`
 `});`
`realm.create("Profile", {`
  `name: "Tim Doe.",`
  `_id: new UUID("882dd631-bc6e-4e0e-a9e8-f07b685fec8c"), // create a _id with a specific UUID value`
 `});`
`});` |

## .NET Field Types 
 The complete reference of supported data types for .Net/C# can be found [here.

| Type Name | Code Sample |
| --- | --- |
| Realm Database supports the following .NET data types and their nullable counterparts:
bool
byte
short
int
long
float
double
decimal
char
string
byte]
DateTimeOffset
Guid
IList, where T is any of the supported data types | Regular C# code, nothing special to see here! |
| ObjectId maps to [BSON `ObjectId` type. |  |

## .Net Field Types: New supported types

Starting with __.NET SDK 10.2.0__

| Type Name | Code Sample |
| --------- | ----------- |
| Dictionary 
A Realm dictionary is an implementation of IDictionary that has keys of type String and supports values of any Realm type except collections. To define a dictionary, use a getter-only IDictionary property, where TValue is any of the supported types. | `public class Inventory : RealmObject` 
`{`
 `// The key must be of type string; the value can be`
 `// of any Realm-supported type, including objects`
 `// that inherit from RealmObject or EmbeddedObject`
 `public IDictionary PlantDict { get; }`
 `public IDictionary BooleansDict { get; }`
 `// Nullable types are supported in local-only`
 `// Realms, but not with Sync`
 `public IDictionary NullableIntDict { get; }`
 `// For C# types that are implicitly nullable, you can`
 `// use the Required] attribute to prevent storing null values`
 `[Required]`
 `public IDictionary RequiredStringsDict { get; }`
`}` |
| [Sets 
A Realm set, like the C# HashSet<>, is an implementation of ICollection<> and IEnumerable<>. It supports values of any Realm type except collections. To define a set, use a getter-only ISet property, where TValue is any of the supported types. | `public class Inventory : RealmObject` 
`{`
 `// A Set can contain any Realm-supported type, including`
 `// objects that inherit from RealmObject or EmbeddedObject`
 `public ISet PlantSet { get; }
public ISet DoubleSet { get; }`
 `// Nullable types are supported in local-only`
 `// Realms, but not with Sync`
 `public ISet NullableIntsSet { get; }`
 `// For C# types that are implicitly nullable, you can`
 `// use the Required] attribute to prevent storing null values`
 `[Required]`
 `public ISet RequiredStrings { get; }`
`}` |
| [RealmValue 
The RealmValue data type is a mixed data type, and can represent any other valid Realm data type except a collection. You can create collections (lists, sets and dictionaries) of type RealmValue, but a RealmValue itself cannot be a collection. | `public class MyRealmValueObject : RealmObject` 
`{`
 `PrimaryKey]`
 `[MapTo("_id")]`
 `public Guid Id { get; set; }`
 `public RealmValue MyValue { get; set; }`
 `// A nullable RealmValue preoprtrty is *not supported*`
 `// public RealmValue? NullableRealmValueNotAllowed { get; set; }`
`}`
`private void TestRealmValue()`
`{`
 `var obj = new MyRealmValueObject();`
 `// set the value to null:`
 `obj.MyValue = RealmValue.Null;`
 `// or an int...`
 `obj.MyValue = 1;`
 `// or a string...`
 `obj.MyValue = "abc";`
 `// Use RealmValueType to check the type:`
 `if (obj.MyValue.Type == RealmValueType.String)`
 `{`
  `var myString = obj.MyValue.AsString();`
 `}`
`}` |
| [Guid and ObjectId Properties 
MongoDB.Bson.ObjectId is a MongoDB-specific 12-byte unique value, while the built-in .NET type Guid is a 16-byte universally-unique value. Both types are indexable, and either can be used as a Primary Key. |  |