Scala:使用函数作为第一类对象的问题
我需要一组通用函数,但我无法按照我喜欢的方式完成它。 我创建了一个
List[(Any)=>Unit]
,但是一旦我尝试插入一个函数,例如 a,
String=>Unit
我就会收到错误。如何声明一个不考虑参数和返回值类型的通用函数集合?
I need to have a collection of generic functions, but I can't get it done in the way I like.
I created a
List[(Any)=>Unit]
but as soon as I try to insert a function, for example a
String=>Unit
I get an error. How could I declare a generic function collection that does not consider parameter and return values types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数在输入类型参数中是逆变的,例如在您的情况下
Function1[-T1,+R]
。这意味着您可以添加Any => 的实例Unit
到List[String =>; Unit]
但反之则不然。这当然是有道理的,因为您不能使用Any
类型的参数来调用需要String
类型的参数的函数。Functions are contravariant in the intput type parameters, e.g. in your case
Function1[-T1,+R]
. This means you can add an instance ofAny => Unit
to aList[String => Unit]
but not the other way round. This of course makes sense as you cannot call a function expecting an argument of typeString
with an argument of typeAny
.为了完成 @Moritz 的回答,您需要为
T1
选择类型参数,它是列表中每个函数的输入类型的子类型。Nothing
符合要求——它是每种类型的子类型。存在主义类型也适用:
Just to finish of
@Moritz
's answer, you need to choose type argument forT1
that is a subtype of the input type of every function in the list.Nothing
fits the bill -- it is a subtype of every type.An existential type also works: