如何引用函数的一个重载?这需要反思吗?
----- Define two functions with the same signature
scala> def f( x:Int ) = x + 1
f: (x: Int)Int
scala> def g( x:Int ) = x + 2
g: (x: Int)Int
----- Define a function that returns one or the other
scala> def pick( a:Boolean ) = if (a) f _ else g _
pick: (a: Boolean)Int => Int
scala> pick(true)(0)
res24: Int = 1
scala> pick(false)(0)
res25: Int = 2
----- All good so far; now overload f to also take a String
scala> def f( x:String ) = x.toInt + 1
f: (x: String)Int
scala> def pick( a:Boolean ) = if (a) f _ else g _
pick: (a: Boolean)String with Int => Int
scala> pick(false)(0)
<console>:12: error: type mismatch;
found : Int(0)
required: String with Int
pick(false)(0)
^
我明白为什么这不起作用。但是如何定义 pick 以使用采用 Int 的 f,而忽略采用 String 的 f?
同样,我不想编写调用 f 或 g 的函数。我想编写一个返回f 或 g 的函数,然后我可以调用无数次。