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 Strings. 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?
Any => Anymap is often an antipattern to be avoided in Scala. Understanding your use case might help answerers identify a better design pattern to use here.String => String,Int => String,Double => Double, etc, so I usedAny =>. These functions are also usuallyT: Numeric => T, so I would like to be able to pass in what typeTis at runtime.