How can I define an anonymous generic Scala function?

后端 未结 2 1616
失恋的感觉
失恋的感觉 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: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] = 
    
    scala> f5("abcdefg")
    res13: java.lang.String = abcd
    
    scala> val f6 = new myfunc[Int]
    f6: myfunc[Int] = 
    
    scala> f6(1234567)
    res14: java.lang.String = 1234
    

提交回复
热议问题