Defining a Map from String to Function in Scala

前端 未结 5 835
粉色の甜心
粉色の甜心 2021-02-05 21:17

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         


        
5条回答
  •  清歌不尽
    2021-02-05 21:17

    Trait Function1 is contravariant for parameter, so def foo(x: Int): String is not a (Any) => String. So the following would work:

    scala> def baz(x: Any): String = "baz"                         
    baz: (x: Any)String
    
    scala> val m2 = Map[String, (String) => String]("hello" -> baz)
    m2: scala.collection.immutable.Map[String,(String) => String] = Map((hello,))
    

提交回复
热议问题