implement type-safe fallback commands
This commit is contained in:
@@ -1,12 +1,24 @@
|
||||
package com.infendro.cli.parser
|
||||
|
||||
import com.infendro.cli.exception.run.InvalidValue
|
||||
import com.infendro.cli.exception.run.RuntimeError
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
interface Parser<T : Any> {
|
||||
val type: KClass<T>
|
||||
abstract class Parser<T : Any>(
|
||||
val type: KClass<T>,
|
||||
) {
|
||||
sealed class Result<T : Any> {
|
||||
data class Success<T : Any>(
|
||||
val value: T,
|
||||
) : Result<T>()
|
||||
|
||||
fun parse(text: String): T
|
||||
data class Failure<T : Any>(
|
||||
val error: RuntimeError,
|
||||
) : Result<T>()
|
||||
}
|
||||
|
||||
fun invalid(text: String): Nothing = throw InvalidValue(text, type)
|
||||
protected fun success(value: T) = Result.Success(value)
|
||||
protected fun failure(text: String) = Result.Failure<T>(InvalidValue(text, type))
|
||||
|
||||
abstract fun parse(text: String): Result<T>
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user