You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
1.9 KiB
83 lines
1.9 KiB
|
5 months ago
|
package com.quillstudios.pokegoalshelper.ml
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Result wrapper for ML operations to standardize error handling
|
||
|
|
*/
|
||
|
|
sealed class MLResult<out T>
|
||
|
|
{
|
||
|
|
data class Success<T>(val data: T) : MLResult<T>()
|
||
|
|
data class Error(val exception: Throwable, val message: String) : MLResult<Nothing>()
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Returns the data if successful, or null if error
|
||
|
|
*/
|
||
|
|
fun getOrNull(): T? = when (this)
|
||
|
|
{
|
||
|
|
is Success -> data
|
||
|
|
is Error -> null
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Returns the data if successful, or the default value if error
|
||
|
|
*/
|
||
|
|
fun getOrDefault(default: T): T = when (this)
|
||
|
|
{
|
||
|
|
is Success -> data
|
||
|
|
is Error -> default
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Execute block if successful
|
||
|
|
*/
|
||
|
|
inline fun onSuccess(block: (T) -> Unit): MLResult<T>
|
||
|
|
{
|
||
|
|
if (this is Success) block(data)
|
||
|
|
return this
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Execute block if error
|
||
|
|
*/
|
||
|
|
inline fun onError(block: (Throwable, String) -> Unit): MLResult<T>
|
||
|
|
{
|
||
|
|
if (this is Error) block(exception, message)
|
||
|
|
return this
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Transform the data if successful
|
||
|
|
*/
|
||
|
|
inline fun <R> map(transform: (T) -> R): MLResult<R> = when (this)
|
||
|
|
{
|
||
|
|
is Success -> try { Success(transform(data)) }
|
||
|
|
catch (e: Exception) { Error(e, "Transform failed: ${e.message}") }
|
||
|
|
is Error -> this
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Helper functions for creating results
|
||
|
|
*/
|
||
|
|
inline fun <T> mlTry(operation: () -> T): MLResult<T>
|
||
|
|
{
|
||
|
|
return try
|
||
|
|
{
|
||
|
|
MLResult.Success(operation())
|
||
|
|
}
|
||
|
|
catch (e: Exception)
|
||
|
|
{
|
||
|
|
MLResult.Error(e, "Operation failed: ${e.message}")
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
inline fun <T> mlTryWithMessage(message: String, operation: () -> T): MLResult<T>
|
||
|
|
{
|
||
|
|
return try
|
||
|
|
{
|
||
|
|
MLResult.Success(operation())
|
||
|
|
}
|
||
|
|
catch (e: Exception)
|
||
|
|
{
|
||
|
|
MLResult.Error(e, "$message: ${e.message}")
|
||
|
|
}
|
||
|
|
}
|