How can I define an anonymous generic Scala functi

2019-01-15 12:46发布

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

2条回答
我只想做你的唯一
2楼-- · 2019-01-15 13:20

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

闹够了就滚
3楼-- · 2019-01-15 13:21

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
查看更多
登录 后发表回答