什么是Scala中所有函数的超类型? [英] What is the supertype of all functions in Scala?
问题描述
我知道我可以对 Function1
或 Function2 $ c>执行
instanceOf
$ c>等,但有没有一种通用的方式来看看是否有功能(它可以有任意数量的参数)。我尝试定义这样的内容:
type FuncType =(Any *) - >任何
但是这也行不通。基本上我有一些代码如下所示:
call =(name:Any,args:Any *) - >如果name.isFunction则name.castAs [Function] .apply(args)else name
aFunction =(name:String)=> Hello+名称
notAFunction =Hello rick
call(aFunction,rick)
call(notAFunction)
不,没有办法做到这一点,除了检查每个 Function1
, Function2
等等。这些特质的父母都是 AnyRef
帮助你区别于其他任何东西。对于这些特征中的每一个,应用
方法都会采用不同数量的参数,因此无法为它们提供具有apply方法的父项。最接近你想要做的是:
$ b $ pre $ def $ function def(function:AnyRef,args:Seq [任何]):任何= {
函数匹配{
case f:Function1 [Any,Any] => f(args(0))
case f:Function2 [Any,Any,Any] => f(args(0),args(1))
//等等
}
}
但是这是疯狂而危险的,如果类型错误,它会在运行时抛出异常,例如
arbitraryFunction((x:Int)=> x * 2,List(I'm a String!))
I know I can do instanceOf
checks against Function1
or Function2
etc but is there a generic way to see if something is function or not (it can have arbitray number of args). I tried defining something like this:
type FuncType = (Any*) -> Any
But that did not work either. Basically I have some code that looks like this:
call = (name: Any, args: Any*) -> if name.isFunction then name.castAs[Function].apply(args) else name
aFunction = (name: String) => "Hello " + name
notAFunction = "Hello rick"
call(aFunction, "rick")
call(notAFunction)
No, there is no way to do this, except to go through and check each of Function1
, Function2
, etc. The parent of each of these traits is AnyRef
, which won't help you to distinguish them from anything else. The apply
method for each of these traits takes a different number of parameters, so there is no way to give them a parent that has an apply method. The closest you could probably get to what you are trying to do is:
def arbitraryFunction(function: AnyRef, args: Seq[Any]): Any = {
function match {
case f: Function1[Any, Any] => f(args(0))
case f: Function2[Any, Any, Any] => f(args(0), args(1))
// and so on
}
}
But this is insane and dangerous and will throw exceptions at runtime if the types are wrong, e.g.
arbitraryFunction((x: Int) => x * 2, List("I'm a String!"))
这篇关于什么是Scala中所有函数的超类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!