Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a Map from String to Function in Scala

Tags:

types

map

scala

I am trying to define a Map literal with key: String, value: (Any)=>String. I tried the following, but get a syntax error:

def foo(x: Int): String = /...
def bar(x: Boolean): String = /...
val m = Map[String, (Any) => String]("hello" -> foo, "goodbye" -> bar)
like image 654
Ralph Avatar asked Jan 06 '11 17:01

Ralph


People also ask

How do I make a map map in Scala?

Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable. Map. While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable.

What is map string string in Scala?

A map represents an mapping from keys to values. The Scala Map type has two type parameters, for the key type and for the value type. So a Map[String, Int] maps strings to integers, while a Map[Int, Set[String]] maps integers to sets of strings. Scala provides both immutable and mutable maps.

Will map function work on string?

Remember that the map function will return a map object. Thus, we can use the string method join, which takes in an iterable (which the map object is, since it is an iterator, and all iterators are iterable), and then joins it into a string.


1 Answers

Funny that no one actually gave a type that would work. Here's one such:

def foo(x: Int): String = x.toString
def bar(x: Boolean): String = x.toString
val m = Map[String, (Nothing) => String]("hello" -> foo, "goodbye" -> bar)

The reason why it works this way is because Function1 is contra-variant on the input, so (Nothing) => String is a superclass of (Int) => String. It is also co-variant on the output, so (Nothing) => Any would be a superclass to any other Function1.

Of course, you can't use it like that. Without manifests, you can't even uncover what the original type of Function1 is. You could try something like this, though:

def f[T : Manifest](v: T) = v -> manifest[T]
val m = Map[String, ((Nothing) => String, Manifest[_])]("hello" -> f(foo), "goodbye" -> f(bar))

val IntManifest = manifest[Int]
val BooleanManifest = manifest[Boolean]
val StringManifest = manifest[String]
m("hello")._2.typeArguments match {
    case List(IntManifest, StringManifest) =>
        m("hello")._1.asInstanceOf[(Int) => String](5)
    case List(BooleanManifest, StringManifest) =>
        m("hello")._1.asInstanceOf[(Boolean) => String](true)
    case _ => "Unknown function type"
}
like image 75
Daniel C. Sobral Avatar answered Sep 28 '22 21:09

Daniel C. Sobral