le-doude
le-doude

Reputation: 3367

How to make a Map string as keys and functions as values in scala?

What I would like to do is something like this :

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},
   ...
)

Is that even possible? How would I achieve that? My goal is to have the function evaluate when I get it from the map.

Upvotes: 0

Views: 81

Answers (1)

mbarlocker
mbarlocker

Reputation: 1386

The closest thing you'll get is a Map[String, () => String]

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

val name1 = myMap("name1")()

You could also create your own map and override the default function

How to implement Map with default operation in Scala

Upvotes: 1

Related Questions