I have two functions with different type signatures, and I want to store them both in a Map:
val add = ((a: Int, b: Int) => a + b)
val odd = ((a: Int) => a % 2 == 0)
var funcs = Map[String, Any]("add" -> add, "odd" -> odd)
Then I want to access these functions at a later date, without having to know about their types. How would I do this? I can write:
funcs("add").asInstanceOf[(Int, Int) => Int](1, 2)
But that requires me to either
- know ahead of time what the type of the function is
- do some sort of pattern match that accounts for every possible type.
Is there some way I can find out the type of the object stored as Any and convert it to that type?
Although this certainly is not a good idea, if you really have to do it, you can do it using reflection.
Using PaulP’s Invocation utility: