Enums support with Realm?

i created a Kotlin delegate, which means a little less repitition

usage:

open class SomeDbModel : RealmObject() {

    @delegate:Ignore
    var variableEnum: MyEnum by enum(::variable)
    private var variable: String = MyEnum.Default.name
}

delegate implementation:

package com.github.ericytsang

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty

inline fun <R, reified T : Enum<T>> enum(
    backingField: KMutableProperty0<Int>
) = OrdinalToEnumDelegate<R, T>(T::class, backingField)

val <T : Enum<T>> KClass<out T>.enumValues get() = java.enumConstants!!.toList()

class StringToEnumDelegate<R, T : Enum<T>>(

    /**
     * enum class to convert the ordinal values in [backingField] to.
     */
    enumClass: KClass<T>,

    /**
     * the property containing [T]'s ordinal value.
     */
    private val backingField: KMutableProperty0<String>

) : ReadWriteProperty<R, T> {

    private val enumValues = enumClass.enumValues.associateBy { it.name }

    override fun getValue(thisRef: R, property: KProperty<*>): T {
        return enumValues[backingField.get()]
            ?: error("no corresponding enum found for ${backingField.get()} in ${enumValues.keys}")
    }

    override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
        backingField.set(value.name)
    }
}

If you need a solution that works on Kotlin you can use the following:

open class Foo: RealmObject() {
    var enum: MyEnum
        get() { return MyEnum.valueOf(enumDescription) }
        set(newMyEum) { enumDescription = newMyEnum.name }
    private var enumDescription: String = MyEnum.FOO.name
}

MyEnum is the enum declared in @ChristianMelchior answer.

It is worth mentioning that since enum doesn't have a backing field,it won't be persisted into Realm. There is no need to use the @Ignore annotation on it


You can use the pattern described in the issue: https://github.com/realm/realm-java/issues/776#issuecomment-190147079

Basically save it as a String in Realm and convert it going in and out:

public enum MyEnum {
  FOO, BAR;
}

public class Foo extends RealmObject {
  private String enumDescription;

  public void saveEnum(MyEnum val) {
    this.enumDescription = val.toString();
  }

  public MyEnum getEnum() {
    return MyEnum.valueOf(enumDescription);
  }
}