Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a delegate to read and mutate an apiEnum backingfield seamlessly #301

Merged
merged 1 commit into from
Feb 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/main/kotlin/com/infomaniak/core/utils/EnumUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
*/
package com.infomaniak.core.utils

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

inline fun <reified T : Enum<T>> enumValueOfOrNull(value: String?): T? {
return value?.let { runCatching { enumValueOf<T>(it) }.getOrNull() }
}
Expand All @@ -25,6 +29,13 @@ inline fun <reified T> apiEnumValueOfOrNull(value: String?): T? where T : Enum<T
return value?.let { runCatching { enumValues<T>().firstOrNull { it.apiValue == value } }.getOrNull() }
}

inline fun <reified T> apiEnum(backingFieldProperty: KMutableProperty0<String?>): ReadWriteProperty<Any?, T?> where T : Enum<T>, T : ApiEnum {
return object : ReadWriteProperty<Any?, T?> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T? = apiEnumValueOfOrNull<T>(backingFieldProperty.get())
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) = backingFieldProperty.set(value?.apiValue)
}
}

interface ApiEnum {
val apiValue: String
}