问题
Let's say I have this:
val myAnon:(Option[String],String)=>String = (a:Option[String],defVal:String) => {
a.getOrElse(defVal)
}
Don't mind what the function does. Is there anyway of making it generic, so I can have an Option[T]?
回答1:
To summarize from that answer: No, you can't make anonymous functions generic, but you can explicitly define your function as a class that extends one of the Function0, Function1, Function2, etc.. traits and define the apply function from those traits. Then the class you define can be generic. Here is the excerpt from the original article, available here:
scala> class myfunc[T] extends Function1[T,String] {
| def apply(x:T) = x.toString.substring(0,4)
| }
defined class myfunc
scala> val f5 = new myfunc[String]
f5: myfunc[String] = <function>
scala> f5("abcdefg")
res13: java.lang.String = abcd
scala> val f6 = new myfunc[Int]
f6: myfunc[Int] = <function>
scala> f6(1234567)
res14: java.lang.String = 1234
回答2:
I don't think anonymous functions can have type parameters. See this answer for details.
来源:https://stackoverflow.com/questions/2554531/how-can-i-define-an-anonymous-generic-scala-function