How can I create a map of Strings to functions with generic types? For example, I want to be able to create a map at compile time:
var unaryFunctionMap: Map[String, Any => Any] = Map[String, Any => Any]()
then I want to add functions that can accept a combination of types of String
, Int
, Double
, etc. Possibly in a way that looks like:
unaryFunctionMap += ("Abs" -> Functions.add)
unaryFunctionMap += ("Neg" -> Functions.neg)
unaryFunctionMap += ("Rev" -> Functions.rev)
Where I implement the actual functions in my Functions
class:
def abs[T: Numeric](value: T)(implicit n: Numeric[T]): T = {
n.abs(value)
}
def neg[T: Numeric](value: T)(implicit n: Numeric[T]): T = {
n.negate(value)
}
def rev(string: String): String = {
string.reverse
}
So, abs
and neg
both permit Numeric
types and rev
only allows for String
s. When I use the map, I want to be able to specify the typing if necessary. Something like this:
(unaryFunctionMap.get("abs").get)[Int](-45)
or, if that isn't possible,
(unaryFunctionMap.get("abs").get)(Int, -45)
How can I modify my code to implement this functionality?