How can I define an anonymous generic Scala function?

后端 未结 2 1605
失恋的感觉
失恋的感觉 2020-12-17 10:58

Let\'s say I have this:

val myAnon:(Option[String],String)=>String = (a:Option[String],defVal:String) => {
  a.getOrElse(defVal)
}

Do

相关标签:
2条回答
  • 2020-12-17 11:15

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

    0 讨论(0)
  • 2020-12-17 11:27

    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
    
    0 讨论(0)
提交回复
热议问题