views:

167

answers:

2

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]?

+5  A: 

I don't think anonymous functions can have type parameters. See this answer for details.

Ben Lings
+2  A: 

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
Jeremy Bell