2017-09-23 23:43:08 -07:00
|
|
|
package org.nwapw.abacus.function
|
2017-08-25 00:43:36 -07:00
|
|
|
|
2017-09-06 22:54:21 -07:00
|
|
|
import org.nwapw.abacus.context.MutableEvaluationContext
|
2017-11-23 02:21:06 -08:00
|
|
|
import org.nwapw.abacus.context.PluginEvaluationContext
|
2017-09-07 13:05:16 -07:00
|
|
|
import org.nwapw.abacus.exception.DomainException
|
2017-09-01 17:45:32 -07:00
|
|
|
|
2017-08-25 00:43:36 -07:00
|
|
|
/**
|
2017-08-25 16:07:23 -07:00
|
|
|
* A class that can be applied to arguments.
|
|
|
|
*
|
|
|
|
* Applicable is a class that represents something that can be applied to one or more
|
2017-08-25 00:43:36 -07:00
|
|
|
* arguments of the same type, and returns a single value from that application.
|
|
|
|
* @param <T> the type of the parameters passed to this applicable.
|
|
|
|
* @param <O> the return type of the applicable.
|
|
|
|
*/
|
2017-08-26 12:19:34 -07:00
|
|
|
interface Applicable<in T : Any, out O : Any> {
|
2017-08-25 00:43:36 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if the given applicable can be used with the given parameters.
|
|
|
|
* @param params the parameter array to verify for compatibility.
|
|
|
|
* @return whether the array can be used with applyInternal.
|
|
|
|
*/
|
2017-11-23 02:21:06 -08:00
|
|
|
fun matchesParams(context: PluginEvaluationContext, params: Array<out T>): Boolean
|
2017-08-26 12:19:34 -07:00
|
|
|
|
2017-08-25 00:43:36 -07:00
|
|
|
/**
|
|
|
|
* Applies the applicable object to the given parameters,
|
|
|
|
* without checking for compatibility.
|
|
|
|
* @param params the parameters to apply to.
|
|
|
|
* @return the result of the application.
|
|
|
|
*/
|
2017-11-23 02:21:06 -08:00
|
|
|
fun applyInternal(context: PluginEvaluationContext, params: Array<out T>): O
|
2017-08-25 00:43:36 -07:00
|
|
|
|
|
|
|
/**
|
|
|
|
* If the parameters can be used with this applicable, returns
|
|
|
|
* the result of the application of the applicable to the parameters.
|
|
|
|
* Otherwise, returns null.
|
|
|
|
* @param params the parameters to apply to.
|
|
|
|
* @return the result of the operation, or null if parameters do not match.
|
|
|
|
*/
|
2017-11-23 02:21:06 -08:00
|
|
|
fun apply(context: PluginEvaluationContext, vararg params: T): O {
|
2017-09-07 13:21:18 -07:00
|
|
|
if (!matchesParams(context, params))
|
|
|
|
throw DomainException("parameters do not match function requirements.")
|
2017-09-06 21:43:07 -07:00
|
|
|
return applyInternal(context, params)
|
2017-08-25 00:43:36 -07:00
|
|
|
}
|
|
|
|
|
2017-08-25 16:07:23 -07:00
|
|
|
}
|