Defining a Map from String to Function in Scala

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

    Int => String is not a subclass of Any => String, rather, the contrary. You can't put (replace) an Int => String function when a code expects Any => String, since that code can apply the function with, say, "hi".

    @Ben suggestion works, but how is it useful? you can't invoke the function once you get it from the Map.

    If you really want to do this, maybe define foo as a partial function:

    val foo: PartialFunction[Any, String] = {case i: Int => ....}
    

    Obviously, this will fail at runtime if you pass it a string, but you can always test if the function is ok for use with your parameter by using isDefinedAt. (another alternative may be manifests, but I don't see the value here)

提交回复
热议问题