如何将一个Map字符串作为键和函数作为scala中的值?

时间:2013-05-07 17:27:01

标签: scala collections functional-programming

我想做的是这样的事情:

val myMap: Map[String, => String] = Map(
  "name1" -> {//functions that does stuff to generate some string},
  "name2" -> {//functions that does something else to return some other string},
   ...
)

这甚至可能吗?我怎么做到这一点? 我的目标是在从地图上获取函数时对函数进行评估。

1 个答案:

答案 0 :(得分:1)

你最接近的是Map [String,()=>字符串]

val myMap = Map(
    "name1" -> { () => generateString() },
    "name2" -> { () => generateString() }
)

val name1 = myMap("name1")()

您还可以创建自己的地图并覆盖默认功能

How to implement Map with default operation in Scala