Question

I'm newbie to Scala and I have question below.

def test() {
  var mapObj = Map(1->'a',"Add"->((x:Int,y:Int)=>(x+y)))
  mapObj("Add")
}
test()

How can I invoke the method "Add" with the parameters x:1 and y:2 and then get the result 3???

Many Appreciate and thanks for your kindly help, waiting for your answers ^_^

Was it helpful?

Solution

The problem is your mapObj is of type Map[Any,Any] and hence mapObj("Add") returns element of type Any (which actually is Function2). Hence the compiler does not let you use it as function. You need to convert it to Function2 and then use it.

scala> val mapObj = Map(1->'a',"Add"->((x:Int,y:Int)=>(x+y)))
mapObj: scala.collection.immutable.Map[Any,Any] = Map(1 -> a, Add -> <function2>
)

scala> mapObj("Add")
res8: Any = <function2>

scala> mapObj("Add").asInstanceOf[scala.Function2[Int,Int,Int]](1,2)
res9: Int = 3

To avoid all this, it is rather recommended that you exclude 1->'a' from your map and just have the map as type Map[Int, Function]

OTHER TIPS

Without the key-value pair 1 -> 'a' this is straightforward.

scala> var mapObj = Map("Add"->((x:Int,y:Int)=>(x+y)))
mapObj: scala.collection.immutable.Map[String,(Int, Int) => Int] = Map(Add -> <function2>)

scala> mapObj.get("Add").get.apply(1,2)
res0: Int = 3

When the keys and values have disparate types Int and String for the keys and Char and Function2 for the values the type inferencer uses the most common super type which is Any. Then you get the type Map[Any, Any] which is difficult to work with.

Try to make the keys have the same type and values have the same type. The type inferencer does the rest and you can use the code above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top