Skip to content

Instantly share code, notes, and snippets.

@pgreze
Created March 16, 2021 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgreze/b1217464e51168ff3a359ee164214418 to your computer and use it in GitHub Desktop.
Save pgreze/b1217464e51168ff3a359ee164214418 to your computer and use it in GitHub Desktop.
Allow to run multiple actions on demand in Kotlin script
import kotlin.Function0
import kotlin.Function1
import kotlin.Function2
import kotlin.Function3
import kotlin.Function4
import kotlin.Function5
import kotlin.system.exitProcess
fun run(
vararg functions: Pair<String, Function<Any>>,
) {
val requestedKey = args.firstOrNull()
val function: Function<*> = requestedKey?.let { key ->
functions.firstOrNull { it.first == key }?.second
} ?: { ->
val actions = functions.joinToString(", ") { it.first }
"Could not find the function $requestedKey, available ones: $actions"
}
val failSafe: Function1<Int, String?> = { nArgs ->
if (args.size != nArgs + 1) "Expected $nArgs arguments but received ${args.size - 1}" else null
}
when (function) {
is Function0<*> ->
failSafe(0) ?: function.invoke()
is Function1<*, *> ->
failSafe(1) ?: (function as Function1<String, *>)
.invoke(args[1])
is Function2<*, *, *> ->
failSafe(2) ?: (function as Function2<String, String, *>)
.invoke(args[1], args[2])
is Function3<*, *, *, *> ->
failSafe(3) ?: (function as Function3<String, String, String, *>)
.invoke(args[1], args[2], args[3])
is Function4<*, *, *, *, *> ->
failSafe(4) ?: (function as Function4<String, String, String, String, *>)
.invoke(args[1], args[2], args[3], args[4])
is Function5<*, *, *, *, *, *> ->
failSafe(5) ?: (function as Function5<String, String, String, String, String, *>)
.invoke(args[1], args[2], args[3], args[4], args[5])
else -> function
}.let {
when (it) {
is Unit -> 0
is Int -> it.toInt()
is String -> 1.apply { println(it) }
else -> 1.apply { println("Unsupported return: $it") }
}
}.also(::exitProcess)
}
fun function(arg1: String, arg2: String) {
println("Called function with $arg1 - $arg2")
}
run(
"help" to { println("Show help message") },
"run" to { success: String ->
println("Success: $success")
val status = success.toBoolean()
println("Run with status: $status")
if (status) 0 else 1
},
"fun" to ::function,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment