refactor: Slightly improve enum extensions and usage (#948)

Use `enumEntries` instead of `enumValues`, which is now recommended.

Replace a `.getOrNull(...) ?: other` with `.getOrElse(...) { other }`.
This commit is contained in:
Nik Clayton 2024-09-26 16:23:48 +02:00 committed by GitHub
parent b6883ebed5
commit 6aa6095cd0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 7 additions and 5 deletions

View File

@ -17,6 +17,8 @@
package app.pachli.core.common.extensions
import kotlin.enums.enumEntries
// Note: Technically these don't have to be extension methods on
// Enum.Companion. You could remove that and write:
//
@ -38,17 +40,17 @@ package app.pachli.core.common.extensions
*
* @see [kotlin.Array.get]
*/
inline fun <reified E : Enum<E>> Enum.Companion.get(ordinal: Int) = enumValues<E>()[ordinal]
inline fun <reified E : Enum<E>> Enum.Companion.get(ordinal: Int) = enumEntries<E>()[ordinal]
/**
* Returns the enum constant with the given [ordinal] value or the result
* of calling the [defaultValue] function if the [ordinal] is out of bounds of
* this enum.
*/
inline fun <reified E : Enum<E>> Enum.Companion.getOrElse(ordinal: Int, defaultValue: (Int) -> E) = enumValues<E>().getOrElse(ordinal, defaultValue)
inline fun <reified E : Enum<E>> Enum.Companion.getOrElse(ordinal: Int, defaultValue: (Int) -> E) = enumEntries<E>().getOrElse(ordinal, defaultValue)
/**
* Returns the enum constant with the given [ordinal] value or `null` if the
* [ordinal] is out of bounds of this enum
*/
inline fun <reified E : Enum<E>> Enum.Companion.getOrNull(ordinal: Int) = enumValues<E>().getOrNull(ordinal)
inline fun <reified E : Enum<E>> Enum.Companion.getOrNull(ordinal: Int) = enumEntries<E>().getOrNull(ordinal)

View File

@ -19,7 +19,7 @@ package app.pachli.core.network.model
import android.text.SpannableStringBuilder
import android.text.style.URLSpan
import app.pachli.core.common.extensions.getOrNull
import app.pachli.core.common.extensions.getOrElse
import app.pachli.core.network.json.Default
import app.pachli.core.network.json.HasDefault
import app.pachli.core.network.parseAsMastodonHtml
@ -101,7 +101,7 @@ data class Status(
companion object {
@JvmStatic
fun getOrUnknown(index: Int) = Enum.getOrNull<Visibility>(index) ?: UNKNOWN
fun getOrUnknown(index: Int) = Enum.getOrElse<Visibility>(index) { UNKNOWN }
@JvmStatic
fun byString(s: String): Visibility {