Defining a Map from String to Function in Scala

前端 未结 5 897
粉色の甜心
粉色の甜心 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:44

    If I let the compiler infer it I seem to get an illegal type:

    scala> val m = Map("hello" -> foo _, "goodbye" -> bar _)
    m: scala.collection.immutable.Map[java.lang.String,(Boolean with Int) => String] =
                    Map((hello,), (goodbye,))
    
    scala> m("hello")(8)
    :9: error: type mismatch;
     found   : Int(8)
     required: Boolean with Int
           m("hello")(8)
    scala> var q = new Boolean with Int
    :5: error: illegal inheritance from final class Boolean
           var q = new Boolean with Int
    

    Anyway, what you want is not the type Any but a generic of "any type" which is _:

    scala> val mm = Map[String, (_) => String]("hello" -> foo _, "goodbye" -> bar _)
    mm: scala.collection.immutable.Map[String,Function1[_, String]] =
                   Map((hello,), (goodbye,))
    

    I just posted a question about how to invoke such functions because I don't actually know.

提交回复
热议问题