我怎样才能定义一个匿名的通用Scala函数? [英] How can I define an anonymous generic Scala function?

查看:124
本文介绍了我怎样才能定义一个匿名的通用Scala函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Let's say I have this:

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

不介意什么该功能确实。有没有反正它是通用的,所以我可以有一个选项[T]?

Don't mind what the function does. Is there anyway of making it generic, so I can have an Option[T]?

推荐答案

,你不能使匿名函数泛化,但是你可以明确地定义你的函数作为一个类来扩展函数0,函数1,函数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

这篇关于我怎样才能定义一个匿名的通用Scala函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆