【问题标题】:What is the supertype of all functions in Scala?Scala 中所有函数的超类型是什么?
【发布时间】:2013-08-31 12:55:59
【问题描述】:

我知道我可以对Function1Function2 等进行instanceOf 检查,但是有没有一种通用的方法来查看某些东西是否正常运行(它可以有任意数量的参数)。我尝试定义这样的东西:

type FuncType = (Any*) -> Any

但这也不起作用。基本上我有一些看起来像这样的代码:

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)

【问题讨论】:

    标签: scala reflection macros functional-programming scala-macros


    【解决方案1】:

    没有适用于所有函数类型的通用超类型。

    Scala 无法抽象出函数的数量。但是,您可能会查看 Shapeless 库,它引入了一个称为 HList 的东西,您可以使用它来抽象函数的数量。

    但是,我认为这并不是您真正需要的。听起来你只想做一个检查,比如“这是一个函数吗?”您可能会认为没有与 arity 无关的 Function 超类型很奇怪,但如果您想对函数做一些有用的事情,您几乎总是需要知道函数的 arity。

    或者,您可以使用函数上的curried 方法执行某些操作,该方法将返回Function1

    【讨论】:

      【解决方案2】:

      不,没有办法做到这一点,除了检查每个Function1Function2 等。每个特征的父级是AnyRef,这对你没有帮助将它们与其他任何东西区分开来。每个特征的 apply 方法采用不同数量的参数,因此无法为它们提供具有 apply 方法的父级。您可能最接近您正在尝试做的事情是:

      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
        }
      }
      

      但是这是疯狂和危险的,如果类型错误,会在运行时抛出异常,例如

      arbitraryFunction((x: Int) => x * 2, List("I'm a String!"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-30
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多